简体   繁体   中英

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.

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

for (index = 0; index < results[1].length; index = index + 2) 
{
    results[1].splice( index, 0, {Keys:"Test"} ); 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM