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

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


当前回答

上面的答案有点烦人,因为在你确定它是一个对象之后,它们没有解释你在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版本中使用;)

其他回答

用于。。。in循环表示对象中的每个属性,因为它就像for循环。您在for中定义了propt。。。在循环中执行以下操作:

    for(var propt in obj){
alert(propt + ': ' + obj[propt]);
}

A代表。。。在循环中迭代对象的可枚举财产。无论您定义哪个变量,或将其放入for。。。在循环中,每次转到它迭代的下一个属性时都会发生更改。for中的变量。。。in循环遍历键,但它的值是键的值。例如:

    for(var propt in obj) {
      console.log(propt);//logs name
      console.log(obj[propt]);//logs "Simon"
    }

您可以看到变量与变量值的区别。相比之下,a for。。。of循环则相反。

我希望这有帮助。

上面的答案有点烦人,因为在你确定它是一个对象之后,它们没有解释你在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版本中使用;)

如果运行Node,我建议:

Object.keys(obj).forEach((key, index) => {
    console.log(key);
});

为了进一步完善接受的答案,值得注意的是,如果使用var object=object.create(null)实例化对象,那么object.hasOwnProperty(property)将触发TypeError。所以为了安全起见,您需要从原型中调用它,如下所示:

for (var property in object) {
    if (Object.prototype.hasOwnProperty.call(object, property)) {
        // do stuff
    }
}

这是为了。。。in语句(MDN、ECMAScript规范)。

您可以将其读为“对于obj对象中的每个属性,依次将每个属性分配给PROPT变量”。