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

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


当前回答

现在,只需添加Symbol.iterator方法,就可以将标准JS对象转换为可迭代对象。然后可以使用for循环并直接访问其值,甚至可以在对象上使用扩展运算符。凉的让我们看看如何做到:

var o={a:1,b:2,c:3},a=[];o[Symbol.iiterator]=函数*(){var ok=对象.keys(this);i=0;而(i<ok长度)产生这个[ok[i++]];};for(o的var值)console.log(value);//或者你甚至可以这样做a=[…o];控制台日志(a);

其他回答

用于。。。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循环则相反。

我希望这有帮助。

在这里,我迭代每个节点并创建有意义的节点名称。如果您注意到,instanceOfArray和instanceOfObject几乎做了相同的事情(在我的应用程序中,我给出了不同的逻辑)

function iterate(obj,parent_node) {
    parent_node = parent_node || '';
    for (var property in obj) {
        if (obj.hasOwnProperty(property)) {
            var node = parent_node + "/" + property;
            if(obj[property] instanceof Array) {
                //console.log('array: ' + node + ":" + obj[property]);
                iterate(obj[property],node)
            } else if(obj[property] instanceof Object){
                //console.log('Object: ' + node + ":" + obj[property]);
                iterate(obj[property],node)
            }
            else {
                console.log(node + ":" + obj[property]);
            }
        }
    }
}

注:我受到了翁德雷·斯文达尔(Ondrej Svejdar)的回答的启发。但此解决方案具有更好的性能和更少的模糊性

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

如果您的环境支持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
}

在ES的最新实现中,您可以使用Object.entries:

for (const [key, value] of Object.entries(obj)) { }

or

Object.entries(obj).forEach(([key, value]) => ...)

如果您只想迭代这些值,请使用Object.values:

for (const value of Object.values(obj)) { }

or

Object.values(obj).forEach(value => ...)