循环JavaScript对象的最安全的方法(Safest way to loop over JavaScript object)

227 IT屋

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

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

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?

解决方案

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]);
    }
}

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

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



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


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



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


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


解决方案

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



  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 。


本文地址:IT屋 » 循环JavaScript对象的最安全的方法