Q: 如何檢查屬性是否存在物件內?

A: 使用in 運算符和 Object.hasOwnProperty都可以。

但hasOwnProperty不會檢查物件繼承的屬性,in運算符可以。

--

 

var myProp = 'prop';
if(myObj.hasOwnProperty(myProp)){
    alert("yes, i have that property");
}

 

Or

 

var myProp = 'prop';
if(myProp in myObj){
    alert("yes, i have that property");
}

 

Or

 

if('prop' in myObj){
    alert("yes, i have that property");
}

 

Note that hasOwnProperty doesn't check for inherited properties, whereas in does. For example 'constructor' in myObj is true, but myObj.hasOwnProperty('constructor') is not.

--

當你檢查屬性是否存在目前的物件內,你或許可以這麼做:

 

var myObject = {
  name: '@tips_js'
};

if (myObject.name) { ... }

 

以上的方法是沒問題的,但是你必須知道對於這個問題有兩個原生的方法,in 運算符和 Object.hasOwnProperty。任何繼承 Object 的都可以使用這兩種方法。

 

觀察之間較大的差別

var myObject = {
  name: '@tips_js'
};

myObject.hasOwnProperty('name'); // true
'name' in myObject; // true

myObject.hasOwnProperty('valueOf'); // false, valueOf 繼承自原型鏈結
'valueOf' in myObject; // true

 

兩者不同的地方在於確認的屬性深度不同。換句話說,如果直接在物件內確認 key 是可用的話,hasOwnProperty 只會回傳 true。然而,在 in 運算符沒辦法分辨之間的屬性是建立在物件或是繼承自原型鏈結的。

這裡有其他的範例:

 

var myFunc = function() {
  this.name = '@tips_js';
};
myFunc.prototype.age = '10 days';

var user = new myFunc();

user.hasOwnProperty('name'); // true
user.hasOwnProperty('age'); // false, 因為 age 是繼承自原型鏈結

 

線上範例確認吧! 確認屬性是否存在在物件內的問題常見錯誤,我推薦閱讀關於這個問題的討論

--

轉自 http://www.jstips.co/zh_tw/javascript/check-if-a-property-is-in-a-object/

https://stackoverflow.com/questions/11040472/how-to-check-if-object-property-exists-with-a-variable-holding-the-property-name

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 dizzy03 的頭像
    dizzy03

    碎碎念

    dizzy03 發表在 痞客邦 留言(0) 人氣()