You are modifying sizetracker
while you are running a forEach
on it.(您正在其上运行forEach
时正在修改sizetracker
。)
I think you might expect it to continue processing the items you add to the list, but it doesn't.(我认为您可能希望它继续处理添加到列表中的项目,但事实并非如此。) Run my example code to see the results.(运行我的示例代码以查看结果。) It 'should' have four elements in the list at the end, but it doesn't because forEach
only iterates as many times as there are elements in the list at the outset.(它“应该”在列表的末尾有四个元素,但这不是因为forEach
只迭代一开始就与列表中的元素一样多的次数。)
var list = ['1'] var n = 2 list.forEach(function (el) { if ( list.length < 5 ) { list.push(n.toString()) n++ } }) console.log(list) console.log(list.length)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…