变量obj={name:“西蒙”,年龄:“20”,服装:{style:“简单”,嬉皮士:假}}for(obj中的var propt){console.log(propt+':'+obj[propt]);}

变量propt如何表示对象的财产?它不是内置方法或属性。为什么它会产生对象中的每个属性?


当前回答

你可以使用Lodash。文件

var obj = {a: 1, b: 2, c: 3};
_.keys(obj).forEach(function (key) {
    ...
});

其他回答

虽然最高评级的答案是正确的,但这里有一个备用用例,即如果您正在迭代一个对象,并希望最终创建一个数组。使用.map而不是forEach

const newObj = Object.keys(obj).map(el => {
    //ell will hold keys 
   // Getting the value of the keys should be as simple as obj[el]
})

你可以使用Lodash。文件

var obj = {a: 1, b: 2, c: 3};
_.keys(obj).forEach(function (key) {
    ...
});

JavaScript中的对象是财产的集合,因此可以在for-each语句中循环。

您应该将obj视为键值集合。

为何在循环中,它创建了一个新变量(varsomeVariable),然后将给定对象的每个属性逐一存储在这个新变量(someVariable)中。因此,如果使用块{},则可以进行迭代。考虑以下示例。

var obj = {
     name:'raman',
     hobby:'coding',
     planet:'earth'
     };

for(var someVariable in obj) {
  //do nothing..
}

console.log(someVariable); // outputs planet

上面的答案有点烦人,因为在你确定它是一个对象之后,它们没有解释你在for循环中做什么:你没有直接访问它!实际上,您只收到了需要应用于OBJ的密钥:

var obj = {
  a: "foo",
  b: "bar",
  c: "foobar"
};

// We need to iterate the string keys (not the objects)
for(var someKey in obj)
{
  // We check if this key exists in the obj
  if (obj.hasOwnProperty(someKey))
  {
    // someKey is only the KEY (string)! Use it to get the obj:
    var myActualPropFromObj = obj[someKey]; // Since dynamic, use [] since the key isn't literally named "someKey"

    // NOW you can treat it like an obj
    var shouldBeBar = myActualPropFromObj.b;
  }
}

这是所有ECMA5安全的。甚至可以在Rhino等蹩脚的JS版本中使用;)