我想将这段代码转换为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 = '---';
}
});
},
答案 0 :(得分:1)
由于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
是相当新的,可能需要填充。)
但是:与仅使用for
循环相比,这确实是间接的:
displayPercentages: function(percentages) {
var fields = document.querySelectorAll(DOMstrings.expensesPercLabel);
for (let index = 0; index < fields.length; ++index) {
const el = fields[index];
if (percentages[index] > 0) {
el.textContent = percentages[index] + '%'
} else {
el.textContent = '---';
}
}
}
...或者为此,使用现在forEach
上的NodeList
(再次,您可以polyfill):
displayPercentages: function(percentages) {
document.querySelectorAll(DOMstrings.expensesPercLabel).forEach((el, index) => {
if (percentages[index] > 0) {
el.textContent = percentages[index] + '%'
} else {
el.textContent = '---';
}
});
}