[英]for let of loop doesn't work?
When I use for in loop, it works, and for of loop just doesn't get anything :( Here is my code 当我使用for循环时,它起作用了,并且for循环什么也没得到:(这是我的代码
'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);
})
also forEach doesn't output anything either~?! 也forEach也什么都不输出〜?!
for-of
cannot iterate through objects (since they are not iterable as per the standard). for-of
不能遍历对象(因为按照标准它们是不可迭代的)。
So you either must use the good old for-in
因此,您要么必须使用旧的
for-in
OR 要么
Use the non-standardised yet Object.entries()
: 使用尚未标准化的
Object.entries()
:
for (const [key, value] of Object.entries(obj)) {
console.log(key, value);
}
templateMap
in your case is an object, not an array, since you assign string keys into it (and JS arrays indexes are numeric within [0; 2^32-1)
range). 在您的情况下,
templateMap
是一个对象,而不是一个数组,因为您在其中分配了字符串键(并且JS数组的索引为[0; 2^32-1)
范围内的数字)。
Is template
numeric? template
是数字的吗? It looks like you're about to misuse an Array as an Object. 看来您即将滥用Array作为对象。 Try
templateMap.push(new Object())
to append to the array instead. 尝试使用
templateMap.push(new Object())
附加到数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.