为什么Object.keys()和...在不同的? [英] Why are Object.keys() and for ... in different?

查看:74
本文介绍了为什么Object.keys()和...在不同的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试做一些浏览器对象发现,找出浏览器内置函数等...

I'm trying to do a bit of browser object discovery, figuring out browser built-ins etc...

我注意到尝试获取时有不同的结果窗口对象的属性(仅供参考我使用的是Chrome版本41.0.2272.89(64位))。

I noticed different results when trying to get at the window object's properties (just FYI I'm using Chrome Version 41.0.2272.89 (64-bit)).

Object.keys(window).length;

返回7个密钥。从文档中,Object.keys()返回对象的可枚举属性。

returns 7 keys. From the docs Object.keys() returns the enumerable properties of an object.

但是文档也说 for ... in 迭代对象的可枚举属性。但是:

But the docs also say that for ... in iterates over the enumerable properties of an object. However:

    var i = 0;
    for (var propertyName in window) {
        i++;
    }

返回177的数量。

为什么会有所不同?它们不应该只返回可枚举属性的数量吗?

Why is this different? Shouldn't they both only be returning the count of enumerable properties?

推荐答案

for-in 循环对象的拥有可枚举属性其原型的可枚举属性(以及原型等)。 Object.keys 仅列出对象的拥有可枚举属性。

for-in loops over the object's own enumerable properties and the enumerable properties of its prototype (and its prototype, etc.). Object.keys only lists the object's own enumerable properties.

所以 Object.keys 像这样构建一个数组某事

So Object.keys builds an array something like this:

var keys = [];
var key;
for (key in object) {
    if (object.hasOwnProperty(key)) { // But using an internal, non-overrideable
                                      // operation, not literally the method
        keys.push(key);
    }
}

注意 hasOwnProperty check(它实际上不是对方法的调用,它是一个内部检查,不能通过替换方法或类似方法来欺骗)。

Note the hasOwnProperty check (it's not really a call to the method, it's an internal check that can't be tricked by replacing the method or similar).

这篇关于为什么Object.keys()和...在不同的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆