判断一个js对象,是否具有某个属性

一个对象,想必我们关注的最多的应该是它上面的属性有哪些吧。那么,怎么判断一个对象是否具有某个属性呢?

 /*下面是一个对比,看看在判断是否包括一个键上面,Object结构和Set结构的写法不同。*/
// 对象的写法
var myObject = {
"mm": "m1",
"height": 1,
"width": 1
};
if(myObject["mm"]){
console.log(myObject["mm"]); // m1
} //最开始报错:mm is not defined, 是因为myObject["mm"]写成了myObject[mm], 没有加引号
if(myObject.width){
console.log(myObject.width); //
}
if(myObject.hasOwnProperty('height')){
console.log(myObject.height); //
} /*判断JS对象是否拥有某属性 两种方式,但稍有区别*/
//1.in运算符
console.log('mm' in myObject); // true
console.log('toString' in myObject); // true
//可看到无论是name,还是原形链上的toString,都能检测到返回true。 //2.hasOwnProperty 方法
console.log(myObject.hasOwnProperty('mm')); // true
console.log(myObject.hasOwnProperty('toString')); // false
//原型链上继承过来的属性无法通过hasOwnProperty检测到,返回false。 /*这个时候,它会输出原型的属性
在很多时候,我们不需要遍历它原型的属性,还有一个原因就是,我们现在用到的对象,
我们不能保证,其他开发人员,有没有,在它的原型上加一些属性呢?所以呢,我们就
过滤一下我们对象的属性吧,这个时候就用到了hasOwnProperty方法*/
Object.prototype.say = "hello"; // 添加到对象Object上面
for(var i in myObject){
console.log(myObject[i]); // m1 1 1 hello
}
var test = [1,2,3,4];
Array.prototype.say = "hello"; //添加到数组Array上面
for(var i in test){
console.log(test[i]); // 1 2 3 4 hello
}
//改进:
Object.prototype.say = "hello"; // 添加到对象Object上面
for(var i in myObject){
if(myObject.hasOwnProperty(i)){
console.log(myObject[i]); // m1 1 1
}
}
var test = [1,2,3,4];
Array.prototype.say = "hello"; //添加到数组Array上面
for(var i in test){
if(test.hasOwnProperty(i)){
console.log(test[i]); // 1 2 3 4
}
}
//ES6中 Set的写法
var set = new Set();
set.add("width");
set.add("height");
if(set.has("width")){
console.log(set); //Set {"width", "height"}
console.log([...set]); // ["width", "height"]
}
上一篇:c++多重继承


下一篇:关于降低android手机摄像头预览分辨率