Why cycle skips an array element?

var str = ' ';
var str_1 = str.split(");
console.log(str_1); //output the elements of the resulting array(3 spaces)
for(var i = 0; i<str_1.length; i++){
 if(str_1[i] == ' '){
 str_1.splice(i, 1);

}
}
console.log(str_1); //displays 1 blank...


Eventually displays:
[ '' , '' , '' ]
[ '' ]
March 23rd 20 at 18:46
2 answers
March 23rd 20 at 18:48
So you remove the item from the array without changing i. For example, was an array
arr = [1,2,3]
you removed the null element
[2, 3]
and now move on to the next iteration, where i=1 and, therefore, take three, skipping two.
It is possible to solve so
var str = ' ';
var str_1 = str.split(");
console.log(str_1); //output the elements of the resulting array(3 spaces)
for(var i = 0; i<str_1.length; i++){
 if(str_1[i] == ' '){
 str_1.splice(i, 1);
i--;
}
}
console.log(str_1); //displays 1 blank...
Thank you very much, because of little experience in programming as something not even thought about it... - Emeral commented on March 23rd 20 at 18:51
March 23rd 20 at 18:50
not run through from beginning to end and from end to beginning and everything will be fine. Why - you have already explained.

Find more questions by tags JavaScript