检查属性
- 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
- }
本文详细介绍了JavaScript中对象的各种操作,包括检查属性、增加属性、删除属性及访问属性的方法,并提供了具体的代码实例。
1534

被折叠的 条评论
为什么被折叠?



