我想将这段代码转换为ES-6。因此,我在第一个示例中使用的for循环必须是for循环。在第二个版本中发生的是,百分比计算的效果与我在控制台中看到的预期的一样,但未在UI中显示。较旧的第一种方法可以正常工作。怎么来的?
// This one works fine
displayPercentages: function(percentages) {
var fields =
document.querySelectorAll(DOMstrings.expensesPercLabel);
var nodeListForEach = function(list, callback) {
for(var i = 0; i < list.length ; i++) {
console.log(list[i], i)
callback(list[i], i)
}
};
nodeListForEach(fields, function(el, index){
if(percentages[index] > 0){
el.textContent = percentages[index] + '%'
}else{
el.textContent = '---';
}
});
},
// Second version has a problem showing percentages in the UI
displayPercentages: function(percentages) {
var fields = document.querySelectorAll(DOMstrings.expensesPercLabel);
var nodeListForEach = function(list, callback) {
for(let [el, index] of list.entries()) {
console.log(el, index)
callback(el, index)
}
};
nodeListForEach(fields, function(el, index){
if(percentages[index] > 0){
el.textContent = percentages[index] + '%'
}else{
el.textContent = '---';
}
});
},
由于for
循环的主体使用了索引,所以最好还是坚持使用for
循环,而不要切换到for-of
。
您可以通过将for-of
展开成一个数组(或使用NodeList
创建一个数组),然后使用if you polyfill it,它为您提供了一个迭代器,其中每个迭代的值都是一个Array.from
数组:
NodeList
((请注意Array.from
是相当新的,可能需要填充。)
但是:与仅使用Array.prototype.entries
循环相比,这确实是非常间接的:
[index, value]
...或者为此,使用现在在displayPercentages: function(percentages) {
var fields = document.querySelectorAll(DOMstrings.expensesPercLabel);
for (const [index, el] of [...fields].entries()) {
if (percentages[index] > 0) {
el.textContent = percentages[index] + '%'
} else {
el.textContent = '---';
}
}
}
上的Array.prototype.entries
(您也可以Array.prototype.entries
):
for