[英]how to push element into array at specific index in loop
When i try: 当我尝试:
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 代码崩溃-它向数组中添加了更多元素,循环不断循环
the code crashes - it adds more element to an array and the loop is going endless
代码崩溃-它向数组中添加了更多元素,循环不断循环
Because index < results[1].length
never fails as you keep on increasing the length of result
by adding elements to it. 因为
index < results[1].length
永远不会失败, result
通过添加元素来不断增加result
的长度。
make it 做了
var length = results[1].length;
for (index = 0; index < length; ++index) {
results[1].splice( index, 0, {Keys:"Test"} );
}
Also, this will keep pointing the index
to the newly added item, so increase the index
as well 此外,这将继续将
index
指向新添加的项目,因此也要增加index
for (index = 0; index < results[1].length; index = index + 2)
{
results[1].splice( index, 0, {Keys:"Test"} );
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.