您的位置:首页 > Web前端 > JavaScript

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

2017-01-02 14:40 746 查看

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

1 /*下面是一个对比,看看在判断是否包括一个键上面,Object结构和Set结构的写法不同。*/
2     // 对象的写法
3     var myObject = {
4         "mm": "m1",
5         "height": 1,
6         "width": 1
7     };
8     if(myObject["mm"]){
9         console.log(myObject["mm"]); // m1
10     } //最开始报错:mm is not defined, 是因为myObject["mm"]写成了myObject[mm], 没有加引号
11     if(myObject.width){
12         console.log(myObject.width); // 1
13     }
14     if(myObject.hasOwnProperty('height')){
15         console.log(myObject.height); // 1
16     }
17
18     /*判断JS对象是否拥有某属性 两种方式,但稍有区别*/
19     //1.in运算符
20     console.log('mm' in myObject); // true
21     console.log('toString' in myObject); // true
22     //可看到无论是name,还是原形链上的toString,都能检测到返回true。
23
24     //2.hasOwnProperty 方法
25     console.log(myObject.hasOwnProperty('mm')); // true
26     console.log(myObject.hasOwnProperty('toString')); // false
27     //原型链上继承过来的属性无法通过hasOwnProperty检测到,返回false。
28
29     /*这个时候,它会输出原型的属性
30      在很多时候,我们不需要遍历它原型的属性,还有一个原因就是,我们现在用到的对象,
31      我们不能保证,其他开发人员,有没有,在它的原型上加一些属性呢?所以呢,我们就
32      过滤一下我们对象的属性吧,这个时候就用到了hasOwnProperty方法*/
33     Object.prototype.say = "hello"; // 添加到对象Object上面
34     for(var i in myObject){
35         console.log(myObject[i]); // m1  1  1  hello
36     }
37     var test = [1,2,3,4];
38     Array.prototype.say = "hello"; //添加到数组Array上面
39     for(var i in test){
40         console.log(test[i]); // 1  2  3  4  hello
41     }
42     //改进:
43     Object.prototype.say = "hello"; // 添加到对象Object上面
44     for(var i in myObject){
45         if(myObject.hasOwnProperty(i)){
46             console.log(myObject[i]); // m1  1  1
47         }
48     }
49     var test = [1,2,3,4];
50     Array.prototype.say = "hello"; //添加到数组Array上面
51     for(var i in test){
52         if(test.hasOwnProperty(i)){
53             console.log(test[i]); // 1  2  3  4
54         }
55     }
56     //ES6中 Set的写法
57     var set = new Set();
58     set.add("width");
59     set.add("height");
60     if(set.has("width")){
61         console.log(set); //Set {"width", "height"}
62         console.log([...set]); // ["width", "height"]
63     }

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: