檢查屬性
var mouse = { "name": "betta", "age": 3, "varieties": "milaoshu" } mouse.hasOwnProperty("name"); // true mouse.hasOwnProperty("sex"); //false
增加屬性
定義個對象 dog,然後賦予各種特性,再賦予 color特性,最後遍歷所有的屬性以及值
var dog={ name:"芒果", type:"會之王", eat:function(){ alert("吃"); } } Object.prototype.color="白色"; var name; for(name in dog){ document.write(name+" "+dog[name]+"<br>") }
效果如下
name 芒果 type 會之王 eat function (){ alert("吃"); } color 白色
刪除屬性
var cat = { "name": "tom", "sex": "man", "color": "yellow" } delete cat.name; cat.sex = undefined; cat.color = null; alert("name屬性是否存在:" + cat.hasOwnProperty("name")); //false alert("sex屬性是否存在:" + cat.hasOwnProperty("sex")); //true alert("color屬性是否存在:" + cat.hasOwnProperty("color")); //true
訪問屬性
var cat = { "name": "tom", "sex": "man", "color": "yellow" } var name1 = cat.name; //通過點操作符來訪問對象屬性 var name2 = cat["name"]; //通過中括號操作符來訪問對象屬性
還有創建對象的兩種方式
var obj = new Object(); obj.name = "MangGuo"; obj.age = 25; var obj = { name : "MangGuo", //name是屬性名,"MangGuo"是值 age : 25 }