当我尝试时:
for (index = 0; index < results[1].length; ++index) {
results[1].splice(index,0,{Keys:"Test"});
}
代码崩溃 - 它向数组添加了更多元素,并且循环无限循环
最佳答案
the code crashes - it adds more element to an array and the loop is going endless
因为index < results[1].length
当您不断增加 result
的长度时,永远不会失败通过向其中添加元素。
成功
var length = results[1].length;
for (index = 0; index < length; ++index) {
results[1].splice( index, 0, {Keys:"Test"} );
}
此外,这将继续指向 index
对于新添加的项目,因此增加 index
还有
for (index = 0; index < results[1].length; index = index + 2)
{
results[1].splice( index, 0, {Keys:"Test"} );
}
关于javascript - 如何将元素插入循环中特定索引处的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48204796/