Last active
April 17, 2023 10:17
-
-
Save drzhbe/5554720 to your computer and use it in GitHub Desktop.
Как удалить элемент массива при переборе элементов массива или что бывает, если использовать метод splice внутри цикла? Описание можно почитать в комментарии к гисту.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Bad method, don't use it. | |
var a = [0,1,2,3,4] | |
for (var i = 0; i < a.length; i++) { | |
console.log(i, a[i]); | |
if (a[i] === 0) { | |
console.log(a); | |
a.splice(i, 1); | |
console.log(a); | |
} | |
} | |
/* | |
0 0 | |
[0, 1, 2, 3, 4] | |
[1, 2, 3, 4] // after splice we are in trap: next iteration i will be 1 and a[1] will be 2, so we missed value 1 | |
1 2 | |
2 3 | |
3 4 | |
*/ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Good method. | |
var a = [0,1,2,3,4] | |
for (var i = 0; i < a.length; i++) { | |
console.log(i, a[i]); | |
if (a[i] === 0) { | |
console.log(a); | |
a.splice(i, 1); | |
i--; | |
console.log(a); | |
} | |
} | |
/* | |
0 0 | |
[0, 1, 2, 3, 4] | |
[1, 2, 3, 4] | |
0 1 | |
1 2 | |
2 3 | |
3 4 | |
*/ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var a = [0,1,2,3,4] | |
for (var i = 0; i < a.length; i++) { | |
console.log(i, a[i]); | |
if (a[i] === 0) { | |
console.log(a); | |
delete a[i]; | |
console.log(a); | |
} | |
} | |
/* | |
0 0 | |
[0, 1, 2, 3, 4] | |
[1: 1, 2: 2, 3: 3, 4: 4] // as we see, now we haven't got first element | |
1 1 | |
2 2 | |
3 3 | |
4 4 | |
*/ | |
/* | |
But what actualy was happen? | |
Let's print to console just variable name | |
-> a | |
will print | |
[undefined × 1, 1, 2, 3, 4] | |
and if we will iterate again it will print our 5 elements including first undefined. | |
*/ | |
for (var i = 0; i < a.length; i++) { | |
console.log(i, a[i]); | |
} | |
/* | |
0 undefined | |
1 1 | |
2 2 | |
3 3 | |
4 4 | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Стаст, как вариант можно использовать копию массива, либо несколько переменных-счётчиков :) Всё зависит от конкретной задлачи, которую ты решаешь