域名网站备案,可以做视频推广的网站有哪些内容,小米公司的网络营销工具,西安网站建设公司都有哪些一个对象#xff0c;想必我们关注的最多的应该是它上面的属性有哪些吧。那么#xff0c;怎么判断一个对象是否具有某个属性呢#xff1f; 1 /*下面是一个对比#xff0c;看看在判断是否包括一个键上面#xff0c;Object结构和Set结构的写法不同。*/2 // 对象的写法3 …一个对象想必我们关注的最多的应该是它上面的属性有哪些吧。那么怎么判断一个对象是否具有某个属性呢 1 /*下面是一个对比看看在判断是否包括一个键上面Object结构和Set结构的写法不同。*/2 // 对象的写法3 var myObject {4 mm: m1,5 height: 1,6 width: 17 };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 } 原文出处 [1] 芒果酱-Jessie, 判断一个js对象是否具有某个属性, https://www.cnblogs.com/xiayu25/p/6242445.html 转载于:https://www.cnblogs.com/ryelqy/p/10104078.html