JavaScript object properties check add delete and access action instances
- 2020-07-21 06:47:37
- OfStack
Check the properties
var mouse = {
"name": "betta",
"age": 3,
"varieties": "milaoshu"
}
mouse.hasOwnProperty("name"); // true
mouse.hasOwnProperty("sex"); //false
Increase the attributes
Define an object, dog, give it attributes, then color, and then iterate over all the attributes and values
var dog={
name:" Mango. ",
type:" The king of the would ",
eat:function(){
alert(" eat ");
}
}
Object.prototype.color=" white ";
var name;
for(name in dog){
document.write(name+" "+dog[name]+"<br>")
}
Results the following
name Mango.
type The king of the would
eat function (){ alert(" eat "); }
color white
Delete the properties
var cat = {
"name": "tom",
"sex": "man",
"color": "yellow"
}
delete cat.name;
cat.sex = undefined;
cat.color = null;
alert("name Whether the attribute exists: " + cat.hasOwnProperty("name")); //false
alert("sex Whether the attribute exists: " + cat.hasOwnProperty("sex")); //true
alert("color Whether the attribute exists: " + cat.hasOwnProperty("color")); //true
To access attributes
var cat = {
"name": "tom",
"sex": "man",
"color": "yellow"
}
var name1 = cat.name; // Object properties are accessed through the dot operator
var name2 = cat["name"]; // Object properties are accessed through the brackets operator
There are also two ways to create objects
var obj = new Object();
obj.name = "MangGuo";
obj.age = 25;
var obj = {
name : "MangGuo", //name It's the property name, "MangGuo" Is the value
age : 25
}