hasOwnProperty是否仍应与for..in语句一起使用 [英] Should hasOwnProperty still be used with for..in statements

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

问题描述

很多博客都说,每当使用 for..in 循环时,都应使用 hasOwnProperty 检查,但是我不明白为什么这是案件.不论是否勾选,我们都将得到相同的结果.

There are a lot of blogs saying that a hasOwnProperty check should be used whenever the for..in loop is used, but I don't understand why that's the case. Both with and without the check we get the same results.

查看此小提琴.

推荐答案

如果要使用 {} 创建基本对象,或者使用 JSON.Parse从JSON获取基本对象 hasOwnProperty 在全球范围内无用.

If you're creating a basic object with {}, or getting it from JSON using JSON.Parse, hasOwnProperty is globally useless.

但是,如果要扩展(使用原型)类",那么它可以帮助您了解是否正在访问自己的属性"(直接属性,包括直接函数).

But if you're extending (using prototype) a "class", then it helps you to know if you're accessing your "own properties" (direct properties, including direct functions).

请注意,一个基本对象至少具有一个(非直接)属性,您可以通过 console.log({}); console.log({}.toString)发现),但这不是无法枚举的,也没有看到 for ... in 循环中:

Note that a basic object has at least one (not direct) property, that you may discover with console.log({}); or console.log({}.toString) but it's not enumerable and not seen in a for... in loop :

for ... in循环不会迭代不可枚举的属性.从内置构造函数(如Array和Object)创建的对象具有从Object.prototype和不可枚举的String.prototype,例如String的indexOf方法或对象的toString方法.循环将遍历所有对象对象或其从对象继承的可枚举属性构造函数的原型(包括任何覆盖内置的原型)属性).

A for...in loop does not iterate over non–enumerable properties. Objects created from built–in constructors like Array and Object have inherited non–enumerable properties from Object.prototype and String.prototype that are not enumerable, such as String's indexOf method or Object's toString method. The loop will iterate over all enumerable properties of the object or that it inherits from its constructor's prototype (including any which overwrite built-in properties).

这篇关于hasOwnProperty是否仍应与for..in语句一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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