JS 与js对象相关的方法

一、给js对象添加新属性的方法
例:给对象obj添加一个“selected”的新属性

var obj={};
obj["selected"]="true";
console.log(obj);  //{selected:"true"}

二、判断js对象是否拥有某属性
1.in运算符

var obj={name:"张三"};
alert("name" in obj);  //true
alert("toString" in obj);  //true

无论是name,还是原型链上的toString,都能检测到,返回true
2.hasOwnProperty方法

var obj={name:"张三"};
alert(obj.hasOwnProperty("name"));  //true
alert(obj.hasOwnProperty("toString"));  //false

原型链上继承过来的属性无法通过hasOwnProperty检测到,返回false

猜你喜欢

转载自blog.csdn.net/weixin_43675447/article/details/88043972