Skip to content

Instantly share code, notes, and snippets.

@drzhbe
Last active April 17, 2023 10:17
Show Gist options
  • Save drzhbe/5554720 to your computer and use it in GitHub Desktop.
Save drzhbe/5554720 to your computer and use it in GitHub Desktop.
Как удалить элемент массива при переборе элементов массива или что бывает, если использовать метод splice внутри цикла? Описание можно почитать в комментарии к гисту.
// 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
*/
// 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
*/
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
*/
@fobos
Copy link

fobos commented May 13, 2013

Оператор delete именно и предназначен для удаления свойств объекта

@fobos
Copy link

fobos commented May 13, 2013

Стаст, как вариант можно использовать копию массива, либо несколько переменных-счётчиков :) Всё зависит от конкретной задлачи, которую ты решаешь

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment