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

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


当前回答

如果您的环境支持ES2017,那么我将推荐Object.entries:

Object.entries(obj).forEach(([key, value]) => {
  console.log(`${key} ${value}`);
});

如Mozillas Object.entries()文档所示:

Object.entries()方法返回给定对象自身的数组可枚举属性[key,value]对,顺序与由…提供。。。in循环(区别在于for in循环还列举了原型链中的财产)。

基本上,使用Object.entries,我们可以放弃旧的for。。。循环中:

// This step is not necessary with Object.entries
if (object.hasOwnProperty(property)) {
  // do stuff
}

其他回答

女孩和男孩们,我们在2019年,我们没有那么多时间打字。。。所以,让我们来做这个酷炫的新花式ECMAScript 2016:

Object.keys(obj).forEach(e => console.log(`key=${e}  value=${obj[e]}`));

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

如果您的环境支持ES2017,那么我将推荐Object.entries:

Object.entries(obj).forEach(([key, value]) => {
  console.log(`${key} ${value}`);
});

如Mozillas Object.entries()文档所示:

Object.entries()方法返回给定对象自身的数组可枚举属性[key,value]对,顺序与由…提供。。。in循环(区别在于for in循环还列举了原型链中的财产)。

基本上,使用Object.entries,我们可以放弃旧的for。。。循环中:

// This step is not necessary with Object.entries
if (object.hasOwnProperty(property)) {
  // do stuff
}
let obj = {"a": 3, "b": 2, "6": "a"}

Object.keys(obj).forEach((item) => {console.log("item", obj[item])})

// a
// 3
// 2

从JavaScript 1.8.5开始,您可以使用Object.keys(obj)获取在对象本身上定义的财产数组(obj.hasOwnProperty(key)返回true的属性)。

Object.keys(obj).forEach(function(key,index) {
    // key: the name of the object key
    // index: the ordinal position of the key within the object 
});

这比使用for in循环更好(更可读)。

这些浏览器支持:

Firefox(壁虎):4(2.0)铬:5Internet Explorer:9

有关更多信息,请参阅Mozilla Developer Network Object.keys()的参考。