使用 Prototype 在 javascript 中迭代对象的每个属性?

有没有使用 PrototypeJavaScript 框架迭代对象的每个属性的方法?

情况是这样的: 我在 JSON 中得到一个 AJAX 响应,看起来像这样:

{foo: 1, bar: 2, barobj: {75: true, 76: false, 85: true}}

如果我对变量 response中的 json 响应求值,我希望能够迭代 response.barobj对象中的每个属性,以查看哪些索引为 true,哪些为 false。

原型有 Object.keys()Object.values(),但奇怪的是似乎没有一个简单的 Object.each()功能!我可以获取 Object.keys ()和 Object.values ()的结果,并在迭代其中一个时交叉引用另一个,但是这种方法非常糟糕,我确信有一种正确的方法可以做到这一点!

105799 次浏览

You should iterate over the keys and get the values using square brackets.

See: How do I enumerate the properties of a javascript object?

EDIT: Obviously, this makes the question a duplicate.

You have to first convert your object literal to a Prototype Hash:

// Store your object literal
var obj = {foo: 1, bar: 2, barobj: {75: true, 76: false, 85: true}}


// Iterate like so.  The $H() construct creates a prototype-extended Hash.
$H(obj).each(function(pair){
alert(pair.key);
alert(pair.value);
});

There's no need for Prototype here: JavaScript has for..in loops. If you're not sure that no one messed with Object.prototype, check hasOwnProperty() as well, ie

for(var prop in obj) {
if(obj.hasOwnProperty(prop))
doSomethingWith(obj[prop]);
}