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

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


当前回答

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]);
    });
}

其他回答

您基本上希望循环遍历对象中的每个属性。

JSFiddle公司

var Dictionary = {
  If: {
    you: {
      can: '',
      make: ''
    },
    sense: ''
  },
  of: {
    the: {
      sentence: {
        it: '',
        worked: ''
      }
    }
  }
};

function Iterate(obj) {
  for (prop in obj) {
    if (obj.hasOwnProperty(prop) && isNaN(prop)) {
      console.log(prop + ': ' + obj[prop]);
      Iterate(obj[prop]);
    }
  }
}
Iterate(Dictionary);

实现这一点的简单明了的方法,即不迭代原型的现代JS,如下所示:

Object.prototype.iterateProperties = ((callback) => {
   Object.keys(obj).filter(key => obj.hasOwnProperty(key)).forEach((key) => {
      callback(key, obj[key]);
   });
});

解释

这段代码在所有对象的原型中创建了一个可以在每个object实例中访问的函数。该函数迭代对象的所有自己的财产,并运行回调函数,该函数为对象中的每个属性获取(键、值)。

使用示例

obj.iterateProperties((key, value) => console.log(key + ': ' + value));

虽然最高评级的答案是正确的,但这里有一个备用用例,即如果您正在迭代一个对象,并希望最终创建一个数组。使用.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具有_.mapValues

常量对象={a: 2,b: 3个}常量res=_.map值(obj,v=>v*2)console.log(res)<script src=“https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js“></script>

从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()的参考。