【问题标题】:for let of loop doesn't work?for let 循环不起作用?
【发布时间】:2016-05-13 10:16:26
【问题描述】:

当我使用 for in 循环时,它可以工作,而 for of 循环却什么也得不到:( 这是我的代码

'use strict'

var match_table = [
  {'project': 'Laveral', 'template': 'Blade'},
  {'project': 'Ember.js', 'template': 'Handlebars'},
  {'project': 'Meteor', 'template': 'Handlebars'},
];

// count project number by template
var templateMap = new Array();
match_table.forEach(function(listItem){
  var template = listItem['template'];
  if (!templateMap[template]) {
    templateMap[template] = new Object();
  }
  templateMap[template]['name'] = template;
  if (templateMap[template]['count']) {
    templateMap[template]['count']++;
  } else {
    templateMap[template]['count'] = 1;
  }
});

//console.log(templateMap);

// for loop fails
for (let value of templateMap) {
  console.log(value);
}

templateMap.forEach(function(item) {
  console.log(item);
})

forEach 也不输出任何东西~?!

【问题讨论】:

    标签: javascript loops for-loop let


    【解决方案1】:

    for-of 无法遍历对象(因为按照标准它们不可迭代)。

    所以你要么必须使用旧的for-in

    使用尚未标准化的Object.entries()

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

    templateMap 在您的情况下是一个对象,而不是数组,因为您将字符串键分配给它(并且 JS 数组索引是 [0; 2^32-1) 范围内的数字)。

    【讨论】:

    • 我很感兴趣Object.entries() 的开销有多大:jsperf.com/object-entries-4711。这远远不能忽视。这是 Python 中 iteritems()item() 的重演。
    • @Kay 它分配了一堆数组,但很有趣,谢谢。
    • @Kay 你应该至少添加 hasOwnProperty 检查。
    • zerkms:JS 数组被限制为 2^32 AFAIR,更大的长度被截断。
    • @Ginden 谢谢,确实我混淆了术语:ecma-international.org/ecma-262/6.0/#sec-object-type
    【解决方案2】:

    template 是数字吗?看起来您将误用数组作为对象。尝试将 templateMap.push(new Object()) 附加到数组中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-13
      • 2013-12-31
      • 1970-01-01
      • 2018-04-22
      • 2018-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多