JavaScript Object Property check, add, delete, and access operations _ javascript skills

Source: Internet
Author: User
This article describes how to check, add, delete, and access operation instances of JavaScript objects, this article provides code examples to explain how to add attributes to an object, check the existence of attributes, and delete and access attributes. For more information, see Check attributes

var mouse = { "name": "betta", "age": 3, "varieties": "milaoshu"} mouse.hasOwnProperty("name"); // truemouse.hasOwnProperty("sex"); //false

Add attribute

Define an object dog, then assign various features, then assign color features, and finally traverse all attributes and values

Var dog = {name: "Mango", type: "King of the Meeting", eat: function () {alert ("eat") ;}} Object. prototype. color = "white"; var name; for (name in dog) {document. write (name + "" + dog [name] +"
")}

The effect is as follows:

Name mango type club king eat function () {alert ("eat");} color white

Delete attributes

Var cat = {"name": "tom", "sex": "man", "color": "yellow"} delete cat. name; cat. sex = undefined; cat. color = null; alert ("whether the name attribute exists:" + cat. hasOwnProperty ("name"); // falsealert ("existence of sex property:" + cat. hasOwnProperty ("sex"); // truealert ("Whether the color attribute exists:" + cat. hasOwnProperty ("color"); // true

Access attributes

Var cat = {"name": "tom", "sex": "man", "color": "yellow"} var name1 = cat. name; // use the dot operator to access the object attribute var name2 = cat ["name"]; // use the brackets operator to access the object attribute

There are two ways to create an object

Var obj = new Object (); obj. name = "MangGuo"; obj. age = 25; var obj = {name: "MangGuo", // name is the property name, and "MangGuo" is the value age: 25}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.