原理解釋
因?yàn)閒or...in...會(huì)遍歷原型鏈寿酌,而且對(duì)象屬性中"enumerable=true"的屬性會(huì)被遍歷出來,而實(shí)際一般遍歷數(shù)組我們只希望取到數(shù)組的直接屬性——索引值就可以了硕蛹。
與此相關(guān)
Object.prototype.hasOwnProperty
This method can be used to determine whether an object has the specified property as a direct property of that object; unlike the in operator, this method does not check down the object's prototype chain.
代碼如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script>
// Somewhere deep in your JavaScript library...
Array.prototype.foo = 1;
var ret=Object.getOwnPropertyDescriptor(Array.prototype,"foo");
console.log(ret);//是因?yàn)閒oo的屬性描述符中enumerable屬性為true,即該屬性可遍歷醇疼。
// Now you have no idea what the below code will do.
var a = [1, 2, 3, 4, 5];
for (var x in a){
// Now foo is a part of EVERY array and
// will show up here as a value of 'x'.
console.log(x);
}
</script>
</body>
</html>
新發(fā)現(xiàn)
為什么length屬性沒有被for...in...遍歷出來呢?
這也與屬性描述符有關(guān)系法焰。
Object.getOwnPropertyDescriptor(a,"length")
Object {value: 5, writable: true, enumerable: false, configurable: false}