[js]为什么不能用for...in...来遍历数组

原理解释

因为for...in...会遍历原型链,而且对象属性中"enumerable=true"的属性会被遍历出来,而实际一般遍历数组我们只希望取到数组的直接属性——索引值就可以了。

与此相关

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);//是因为foo的属性描述符中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>

新发现

为什么length属性没有被for...in...遍历出来呢?
这也与属性描述符有关系。

Object.getOwnPropertyDescriptor(a,"length")
Object {value: 5, writable: true, enumerable: false, configurable: false}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容