首页 > 解决方案 > Try to put space between items with splice function but when reload page crash (javascript)

问题描述

I want to put space between the items of an array but when I reload the webpage it crash

Here's part of the code:

array = ['a', 'b', '2', 'c'];

for(i = 0; i < array.length; i++){

    if(array[i + 1] === '2'){

        array.splice(i + 2, 0, ' ');

    }else{

        array.splice(i + 1, 0, ' ');

    }

}

标签: javascriptarrays

解决方案


You have infinite loop in your code; You are iterating not over original array, but the array you modify with each loop pass. Consider changing your code into:

array = ['a', 'b', '2', 'c'];
len = array.length;


for(i = 0; i < len ; i++){

    if(array[i + 1] === '2'){

        array.splice(i + 2, 0, ' ');

    }else{

        array.splice(i + 1, 0, ' ');

}

推荐阅读