В этой статье объясняется, как удалять элементы из массива JavaScript.
В следующем примере мы определяем пользовательский метод для удаления элементов массива:
Пример
Array.prototype.removeByValue = function (val) {
for (var i = 0; i < this.length; i++) {
if (this[i] === val) {
this.splice(i, 1);
i--;
}
}
return this;
}
var sites = ['apple', 'google', 'example', 'taobao'];
sites.removeByValue('google');
console.log(sites);
// -> ['apple', 'example', 'taobao']
for (var i = 0; i < this.length; i++) {
if (this[i] === val) {
this.splice(i, 1);
i--;
}
}
return this;
}
var sites = ['apple', 'google', 'example', 'taobao'];
sites.removeByValue('google');
console.log(sites);
// -> ['apple', 'example', 'taobao']
Попробуйте сами »
Вы также можете использоватьarray.spliceметод для реализации:
Пример
const array = [2, 5, 9];
console.log(array);
const index = array.indexOf(5);
if (index > -1) {
array.splice(index, 1); // Второй параметр — количество удаляемых элементов; установите 1, чтобы удалить только один.
}
// array = [2, 9]
console.log(array);
console.log(array);
const index = array.indexOf(5);
if (index > -1) {
array.splice(index, 1); // Второй параметр — количество удаляемых элементов; установите 1, чтобы удалить только один.
}
// array = [2, 9]
console.log(array);
Попробуйте сами »
В следующем примере показано, как удалить один или несколько элементов из массива:
Пример
function removeItemOnce(arr, value) {
var index = arr.indexOf(value);
if (index > -1) {
arr.splice(index, 1);
}
return arr;
}
function removeItemAll(arr, value) {
var i = 0;
while (i < arr.length) {
if (arr[i] === value) {
arr.splice(i, 1);
} else {
++i;
}
}
return arr;
}
// Использование
console.log(removeItemOnce([2,5,9,1,5,8,5], 5))
console.log(removeItemAll([2,5,9,1,5,8,5], 5))
var index = arr.indexOf(value);
if (index > -1) {
arr.splice(index, 1);
}
return arr;
}
function removeItemAll(arr, value) {
var i = 0;
while (i < arr.length) {
if (arr[i] === value) {
arr.splice(i, 1);
} else {
++i;
}
}
return arr;
}
// Использование
console.log(removeItemOnce([2,5,9,1,5,8,5], 5))
console.log(removeItemAll([2,5,9,1,5,8,5], 5))
Попробуйте сами »