【问题标题】:Cannot iterate through JavaScript object无法遍历 JavaScript 对象
【发布时间】:2016-11-01 13:55:17
【问题描述】:

作为练习,我正在尝试学习如何打印 JS 对象的键和值。我很难过。

以下是我写的一个基本对象,只想打印出key : value

var obTest = {
    name: "John",
    WeddingDate: "10/18/2008",
    NumberKids: "2",
    Website: "www.samplewebsite.com
};


/* VERSION 1
for (var key in obTest) {
    // skip loop if the property is from prototype
    if (!obTest.hasOwnProperty(key)) continue;

    var obKey = obTest[key];
    for (var obProp in obKey) {
        // skip loop if the obProperty is from prototype
        if(!obKey.hasOwnProperty(obProp)) continue;

        // your code
        alert(obProp + " : " + obKey[obProp]);
    }
};
    // note: this prints each character as a key:value
*/

/* VERSION 2
for (var key in obTest) {
   if (obTest.hasOwnProperty(key)) {
      var obKey = obTest[key];
      for (var prop in obKey) {
         if (obKey.hasOwnProperty(prop)) {
            console.log(prop + " : " + obKey[prop]);
         }
      }
   }
};
    // note: this prints each character as a key:value
*/


// VERSION 3
Object.keys(obTest.forEach(function(key) {
    console.log(key, obTest[key]);
}));
    // note: this gives me a breakpoint and can't figure out why it does not work

如前所述,VERSION 1 和 VERSION 2 打印相同的输出,如下所示:

0 : J
1 : o
2 : h
3 : n
0 : 1
1 : 0
2 : /
3 : 1
4 : 8
5 : /
6 : 2
7 : 0
8 : 0
9 : 8
0 : 2
0 : w
1 : w
2 : w
3 : .
4 : s
5 : a
6 : m
7 : p
8 : l
9 : e
10 : w
11 : e
12 : b
13 : s
14 : i
15 : t
16 : e
17 : .
18 : c
19 : o
20 : m

我使用 VERSION 3 的 Visual Studio Code 获得了一个断点。

请帮我做一个这样的输出:

    name : John
    WeddingDate : 10/18/2008
    NumberKids : 2
    Website : www.samplewebsite.com

我不想有数字键,尤其是那些重复的。我读的其他文章似乎没有任何意义。 Python 在迭代和打印对象键和值方面似乎非常简单。

谢谢!

【问题讨论】:

    标签: javascript object for-loop


    【解决方案1】:

    您正在使用两个嵌套循环,而一个就足够了:

    for (var key in obTest) {
      // skip loop if the property is from prototype
      if (!obTest.hasOwnProperty(key)) continue;
      //find the object corresponding to the current key
      var obKey = obTest[key];
      //output the key and the corresponding object  
      alert(key + " : " + obKey);
    };
    

    在您的第二个循环中,您枚举对象的每个值内的所有“键:值”对。对于字符串“John”,键值对是 (0:"J", 1:"o", 2:"h", 3:"n")

    对于第 3 版,括号错误:

    Object.keys(obTest) //close parenthesis of keys here
          .forEach(function(key) {
             console.log(key, obTest[key]);  
           });  //close only forEach here
    

    【讨论】:

      【解决方案2】:

      第三次尝试很有希望,但实施错误。要获得所需的输出,您可以使用

      function objectString(obj) {
          var keys = Object.keys(obj);
          return keys.map(v => v + ": " + obj[v]).join("\n");
      }
      
      console.log(objectString(obTest));
      

      【讨论】:

        【解决方案3】:

        只需使用MDN Docs中的示例

        for (var property in obTest) {
            if( obTest.hasOwnProperty( property ) ) {
               console.log(property + ": " + obTest[property])
            }
        }
        

        其中一个问题是您在“网站”属性的值后面缺少"

        http://codepen.io/anon/pen/ozKENQ

        【讨论】:

          【解决方案4】:

          使用 Object.keys() 获取对象的键列表。然后迭代以获取它们的值。

          var obTest = {
              name: "John",
              WeddingDate: "10/18/2008",
              NumberKids: "2",
              Website: "www.samplewebsite.com" };
          
          Object.keys(obTest).forEach(function(key){        
              if (obTest.hasOwnProperty(key)){
                  console.log(key + ":" + obTest[key]); 
              }
          });
          

          【讨论】:

          • forEach 会跳过具有自己属性的对象,例如 obTest.hasOwnProperty。如果不是,因为我喜欢简洁的代码,我该如何添加它?
          • forEach 只是一个遍历数组的函数。
          • 我已将答案更新为仅打印自己的财产。
          【解决方案5】:

          Object.keys(your_object) 是你的朋友,它将对象转换为数组。查看文档here

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2017-12-17
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2018-07-15
            相关资源
            最近更新 更多