for..in和hasOwnProperty [英] for..in and hasOwnProperty

查看:179
本文介绍了for..in和hasOwnProperty的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<强>可能重复:结果,
如何查看对象在Javascript中是否具有属性?

我在Twitter的JS文件中找到了以下片段。我想知道为什么他们需要调用 hasOwnProperty 函数来查看字典财产? for循环正在为'dict'中的每个'key'运行,这意味着'dict'有'key',我错过了一个点吗?

I found the following snippet in Twitter's JS files. I was wondering why do they need to call the hasOwnProperty function to see dict has the key property? The for loop is running for each 'key' in 'dict' which means 'dict' has 'key', am I missing a point?

function forEach(dict, f) {
    for (key in dict) {
        if (dict.hasOwnProperty(key))
            f(key, dict[key]);
    }
}


推荐答案

因为如果你不这样做,它将循环遍历原型链上的每个属性,包括那些你不知道的属性(可能是由于某人搞乱了原生对象原型而添加的)。

Because if you don't, it will loop through every property on the prototype chain, including ones that you don't know about (that were possibly added by somebody messing with native object prototypes).

通过这种方式,您只能保证该对象实例本身的键。

This way you're guaranteed only the keys that are on that object instance itself.

这篇关于for..in和hasOwnProperty的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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