hasOwnProperty()函式程式碼例項

antzone發表於2017-03-21

此函式可以判斷一個屬性是否是指定物件的自有屬性,所謂的就是非繼承屬性,下面就通過程式碼例項介紹一下關於此函式的用法,希望能夠給需要的朋友帶來一定的幫助。

程式碼如下:

[JavaScript] 純文字檢視 複製程式碼
var theArray=["antzone","螞蟻部落","青島市南區",2];
for(var index in theArray){
  console.log(index+":"+theArray[index]);
}

以上程式碼使用for in語句遍歷了陣列上的所有元素,輸出,再來看一段程式碼例項:

[JavaScript] 純文字檢視 複製程式碼
Array.prototype.target="分享互助";
var theArray=["antzone","螞蟻部落","青島市南區",2];
for(var index in theArray){
  console.log(index+":"+theArray[index]);
}

以上程式碼不但遍歷了陣列元素,而且把繼承的屬性也遍歷了,這往往並不是我們所需要的,程式碼修改如下:

[JavaScript] 純文字檢視 複製程式碼
Array.prototype.target="分享互助";
var theArray=["antzone","螞蟻部落","青島市南區",2];
for(var index in theArray){
  if(theArray.hasOwnProperty(index)){
    console.log(index+":"+theArray[index]);    
  }
}

此函式返回值是一個布林型,如果為真,說明是自有屬性。

相關文章