如何从数组中删除一个特定值? 类似 :

array.remove(value);

制约:我必须使用核心 JavaScript 。 框架不允许 。


当前回答

最简单的方法可能是使用过滤功能。例如:

让数组 = ["哈罗","世界"] 让新数组 = 数组. filter (项目 \\\ 项 ! =@ hello ) ; 控制台. log (新数组) ; // ["世界" ]

其他回答

我喜欢这个单行道:

arr.includes(val) && arr.splice(arr.indexOf(val), 1)

ES6 (无互联网探索者支持) 清除已就位 。 快速 : 没有重复重复或重复 。 支持删除无定义或未定义的值

作为原型

// remove by value. return true if value found and removed, false otherwise
Array.prototype.remove = function(val)
{
    return this.includes(val) && !!this.splice(this.indexOf(val), 1);
}

(是的,我读了所有其他的答案 找不到一个结合的答案 包含和串联在同一行。 )

spolice () 函数能够将数组中的项目还给您, 从特定的索引中删除项目 / 项 :

函数删除 ArrayText( index, 数组) { 数组. splice( index, 1); 返回数组; } 让数组 = [ 1, 2, 3,4]; 让 index = 2; 数组 = 删除 ArrayText( index, 数组); 控制台. log( 数组);

如果你想删除几个项目, 我发现这是最容易的:

const oldArray = [1, 2, 3, 4, 5]
const removeItems = [1, 3, 5]

const newArray = oldArray.filter((value) => {
    return !removeItems.includes(value)
})

console.log(newArray)

产出:

[2, 4]

从带有数组元素的阵列列表中获取阵列和索引 从使用地图toint () 和 Toarray () 方法的阵列新阵列中删除 使用删除 () 方法删除具体索引元素 返回格式化的阵列

使用 jQuery 的阵列 :

A = [1, 2, 3, 4, 5, 6];
A.splice($.inArray(3, A), 1);
//It will return A=[1, 2, 4, 5, 6]`   

注意: 如果元素未找到, 在阵列中返回 - 1 。