一個對象,想必我們關注的最多的應該是它上面的屬性有哪些吧。那么,怎么判斷一個對象是否具有某個屬性呢?
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 }