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

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


当前回答

检查类型

您可以检查propt如何表示对象属性

typeof propt

发现它只是一个字符串(属性名称)。由于for in js“内置”循环的工作方式,它会生成对象中的每个属性。

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

其他回答

jquery允许您立即执行以下操作:

$.each( obj, function( key, value ) {
  alert( key + ": " + value );
});

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

Object.keys(obj).forEach(e => console.log(`key=${e}  value=${obj[e]}`));
if (typeof obj === 'object' && obj !== null) {
    Object.keys(obj).forEach(key => {
        console.log("\n" + key + ": " + obj[key]);
    });
}

// *** Explanation line by line ***

// Explaining the bellow line
// It checks if obj is neither null nor undefined, which means it's safe to get its keys. 
// Otherwise it will give you a "TypeError: Cannot convert undefined or null to object" if obj is null or undefined.
// NOTE 1: You can use Object.hasOwnProperty() instead of Object.keys(obj).length
// NOTE 2: No need to check if obj is an array because it will work just fine.
// NOTE 3: No need to check if obj is a string because it will not pass the 'if typeof obj is Object' statement.
// NOTE 4: No need to check if Obj is undefined because it will not pass the 'if type obj is Object' statement either.
if (typeof obj === 'object' && obj !== null) {

    // Explaining the bellow line
    // Just like in the previous line, this returns an array with
    // all keys in obj (because if code execution got here, it means 
    // obj has keys.) 
    // Then just invoke built-in javascript forEach() to loop
    // over each key in returned array and calls a call back function 
    // on each array element (key), using ES6 arrow function (=>)
    // Or you can just use a normal function ((key) { blah blah }).
    Object.keys(obj).forEach(key => {

        // The bellow line prints out all keys with their 
        // respective value in obj.
        // key comes from the returned array in Object.keys(obj)
        // obj[key] returns the value of key in obj
        console.log("\n" + key + ": " + obj[key]);
    });
}

如果运行Node,我建议:

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

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