JavaScript如何判斷對象有某屬性
判斷對象中是否有某屬性的常見方式總結,不同的場景要使用不同的方式。
一、點( . )或者方括號( [ ] )
通過點或者方括號可以獲取對象的屬性值,如果對象上不存在該屬性,則會返回undefined。當然,這里的“不存在”指的是對象自身和原型鏈上都不存在,如果原型鏈有該屬性,則會返回原型鏈上的屬性值。
// 創建對象let test = {name : ’lei’}// 獲取對象的自身的屬性test.name //'lei'test['name'] //'lei'// 獲取不存在的屬性test.age //undefined// 獲取原型上的屬性test['toString'] //toString() { [native code] }// 新增一個值為undefined的屬性test.un = undefinedtest.un //undefined 不能用在屬性值存在,但可能為 undefined的場景
所以,我們可以根據 Obj.x !== undefined 的返回值 來判斷Obj是否有x屬性。
這種方式很簡單方便,局限性就是:不能用在x的屬性值存在,但可能為 undefined的場景。 in運算符可以解決這個問題
二、 in 運算符
MDN 上對in運算符的介紹:如果指定的屬性在指定的對象或其原型鏈中,則in 運算符返回true。
’name’ in test //true’un’ in test //true’toString’ in test //true’age’ in test //false
示例中可以看出,值為undefined的屬性也可正常判斷。
這種方式的局限性就是無法區分自身和原型鏈上的屬性,在只需要判斷自身屬性是否存在時,這種方式就不適用了。這時需要hasOwnProperty()
三、hasOwnProperty()
test.hasOwnProperty(’name’) //true 自身屬性test.hasOwnProperty(’age’) //false 不存在test.hasOwnProperty(’toString’) //false 原型鏈上屬性
可以看到,只有自身存在該屬性時,才會返回true。適用于只判斷自身屬性的場景。
四、propertyIsEnumerable()
const object1 = {};const array1 = [];object1.property1 = 42;array1[0] = 42;console.log(object1.propertyIsEnumerable(’property1’));// expected output: trueconsole.log(array1.propertyIsEnumerable(0));// expected output: trueconsole.log(array1.propertyIsEnumerable(’length’));// expected output: false
propertyIsEnumerable() 方法返回一個布爾值,表示指定的屬性是否可枚舉。
總結
四種方式各有優缺點,不同的場景使用不同的方式,有時還需要結合使用,比如遍歷自身屬性的時候,就會把 for ··· in ···和 hasOwnProperty()結合使用。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。
相關文章: