循环JavaScript对象的最安全的方法 [英] Safest way to loop over JavaScript object

查看:359
本文介绍了循环JavaScript对象的最安全的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个对象来保存一堆属性,比如

I want to create an object to hold a bunch of properties like

var o = {x: 20, y: 40, color: 'red'};

可以在对象的整个生命周期中添加更多属性,所以我想要一种通用的循环方式在属性上稍后设置它们。我知道 Object.prototype 是否已被搞砸了,只需

More properties can be added to the object throughout its life, so I would like a generic way to loop over the properties to set them later. I know if the Object.prototype has been messed with, simply

for(var prop in o) { ... }

将导致其属性也被循环。还有什么其他的东西会导致这个问题陷入困境,最安全的循环方式是什么?

will cause its properties to also be looped over. What other things can cause this to mess up, and what is the safest way to loop like this?

推荐答案

如果你想要迭代对象上的所有属性,然后继承的属性是您必须处理的唯一真正的问题。 Object.prototype.hasOwnProperty()方法可用于确认属性直接存在于对象中,而不仅仅是继承。

If you want to iterate over all of the properties on an object, then inherited properties are the only real problem you have to deal with. The Object.prototype.hasOwnProperty() method can be used to confirm that a property exists directly an object, and isn't just inherited.

Object.prototype.example = 2;
var o = {x: 4, y: 6};

for (var prop in o) {
    if (Object.prototype.hasOwnProperty.call(o, prop)) {
        console.log(o[prop]);
    }
}

这将打印对象本身的所有属性,但它不会打印继承的 .example

This will print all of the properties of the object itself, but it won't print the inherited .example.

这篇关于循环JavaScript对象的最安全的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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