兩種判斷方法:1、用in關(guān)鍵字,可檢測對象是否有指定屬性,語法“屬性名 in 對象”,若返回true則包含,反之不包含。2、用hasOwnProperty()函數(shù),語法“對象.hasOwnProperty(屬性名)”,若返回true則包含。
本教程操作環(huán)境:windows7系統(tǒng)、ECMAScript 6版、Dell G3電腦。
在es6中,可以使用indexOf()、includes()等方法來檢查數(shù)組中是否包含某個元素。
那么怎么檢查對象?判斷對象中是否包含某個屬性?
方法1:使用in關(guān)鍵字
作用:檢測屬性是否存在對象中,可以使用in關(guān)鍵字來檢測當(dāng)前對象是否有指定屬性
語法:
屬性名 in 對象
判斷屬性名是否在對象中存在,返回一個布爾值
示例:
const person = { name: '小愛', salary: 23 }; console.log('salary' in person); // true console.log('sex' in person); // false
方法2:使用hasOwnProperty()函數(shù)
可以判斷對象中是否含有某個屬性名,返回一個布爾值
對象.hasOwnProperty(屬性名)
示例:
const person = { name: '小愛', salary: 23 }; person.hasOwnProperty('salary') console.log(person.hasOwnProperty('salary')); // true console.log(person.hasOwnProperty('sex')); // false
【