for-in迴圈(for-in Loops)

來源:互聯網
上載者:User

標籤:style   blog   color   使用   io   for   ar   cti   

有個很重要的hasOwnProperty()方法,當遍曆對象屬性的時候可以過濾掉從原型鏈上下來的屬性。

 

// 對象
var man = {
hands: 2,
legs: 2,
heads: 1
};

// 在代碼的某個地方
// 一個方法添加給了所有對象
if (typeof Object.prototype.clone === "undefined") {
Object.prototype.clone = function () {};
}


// 1.
// for-in 迴圈
for (var i in man) {
if (man.hasOwnProperty(i)) { // 過濾
console.log(i, ":", man[i]);
}
}
/* 控制台顯示結果
hands : 2
legs : 2
heads : 1
*/
// 2.
// 反面例子:
// for-in loop without checking hasOwnProperty()
for (var i in man) {
console.log(i, ":", man[i]);
}
/*
控制台顯示結果
hands : 2
legs : 2
heads : 1
clone: function()
*/

另外一種使用hasOwnProperty()的形式是取消Object.prototype上的方法。像是:


for (var i in man) {
if (Object.prototype.hasOwnProperty.call(man, i)) { // 過濾
console.log(i, ":", man[i]);
}
}

其好處在於:在man對象重新定義hasOwnProperty情況下,避免命名衝突;也避免了長屬性尋找對象的所有方法,你可以使用局部變數“緩衝”它。

var i, hasOwn = Object.prototype.hasOwnProperty;
for (i in man) {
if (hasOwn.call(man, i)) { // 過濾
console.log(i, ":", man[i]);
}
}
 

嚴格來說,不使用hasOwnProperty()並不是一個錯誤。根據任務以及你對代碼的自信程度,你可以跳過它以提高些許的迴圈速度。但是當你對當前對象內容(和其原型鏈)不確定的時候,添加hasOwnProperty()更加保險些。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.