JavaScript學習筆記——判斷某個屬性是否屬於某個對象

1. 直接用.或[]判斷

var test = {name : 'lei'}
test.name            //"lei"
test["name"]         //"lei"
// 獲取原型上的屬性
test["toString"]     //toString() { [native code] }
// 新增一個值爲undefined的屬性
test.un = undefined

所以,我們可以根據 Obj.x !== undefined 的返回值 來判斷Obj是否有x屬性。

這種方式很簡單方便,侷限性就是:不能用在x的屬性值存在,但可能爲 undefined的場景。 in運算符可以解決這個問題

2. in 運算符

var test = {name : 'lei'}
console.log("in",'un' in test, 'name' in test,'abc' in test);
//in true true false

這種方式的侷限性就是無法區分自身和原型鏈上的屬性,在只需要判斷自身屬性是否存在時,這種方式就不適用了。同時不是所有的瀏覽器都支持這個語法,存在兼容性問題

3. Reflect.has(obj,name);

Reflect.has方法對應name in obj 中的運算符

var myObject ={foo:1}
//舊寫法
'foo' in myObject ;
// 新寫法
Reflect.has(myObject ,'foo');

如果第一個參數不是對象Rellect.has和in運算符都會報錯

4.hasOwnProperty

test.hasOwnProperty('name')        //true   自身屬性
test.hasOwnProperty('age')           //false  不存在
test.hasOwnProperty('toString')    //false  原型鏈上屬性

可以看到,只有自身存在該屬性時,纔會返回true。適用於只判斷自身屬性的場景

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章