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: true console.log(array1.propertyIsEnumerable(0)); // expected output: true console.log(array1.propertyIsEnumerable('length')); // expected output: false
propertyIsEnumerable() 方法返回一個布林值,表示指定的屬性是否可列舉。
總結
四種方式各有優缺點,不同的場景使用不同的方式,有時還需要結合使用,比如遍歷自身屬性的時候,就會把 for ··· in ···和 hasOwnProperty()結合使用。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。