JavaScript 删除数组元素

本文介绍如何删除 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', 'runoob', 'taobao'];

sites.removeByValue('google');

console.log(sites);

// -> ['apple', 'runoob', 'taobao']

尝试一下 »

也可以使用 array.splice 方法来实现:

实例

const array = [2, 5, 9];

console.log(array);

const index = array.indexOf(5);

if (index > -1) {

array.splice(index, 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;

}

// Usage

console.log(removeItemOnce([2,5,9,1,5,8,5], 5))

console.log(removeItemAll([2,5,9,1,5,8,5], 5))

尝试一下 »


翳乐是什么意思
《崩坏3》数海寻馔三期菜谱汇总