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

array.remove(value);

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


当前回答

虽然大多数先前的答复都回答了这个问题,但是为什么没有使用切片()方法还不够清楚。 是的,过滤器()符合不可改变的标准,但做以下更短的等值如何?

const myArray = [1,2,3,4];

现在让我们说我们应该从阵列中删除第二个元素, 我们可以简单地做到:

const newArray = myArray.slice(0, 1).concat(myArray.slice(2, 4));

// [1,3,4]

今天,社区强烈鼓励从阵列中删除元素,因为其简单和不可改变的性质。 一般来说, 导致突变的方法应该避免。 例如, 鼓励您将推( ) 替换为 concat () , 并用切片 () 替换为 plus () 。

其他回答

使用$.inAray, 以其价值删除一个元素:

$(document).ready(function(){
    var arr = ["C#","Ruby","PHP","C","C++"];
    var itemtoRemove = "PHP";
    arr.splice($.inArray(itemtoRemove, arr),1);
});

除了所有这些解决方案之外, 它也可以用阵列来完成. 减量...

const removeItem = 
    idx => 
    arr => 
    arr.reduce((acc, a, i) =>  idx === i ? acc : acc.concat(a), [])

const array = [1, 2, 3]
const index = 1

const newArray = removeItem(index)(array) 

console.log(newArray) // logs the following array to the console : [1, 3]

...或者一个循环函数(诚实地说不是那么优雅...也许有人有更好的循环解决方案? ? )...

const removeItemPrep = 
    acc => 
    i => 
    idx => 
    arr => 

    // If the index equals i, just feed in the unchanged accumulator(acc) else...
    i === idx ? removeItemPrep(acc)(i + 1)(idx)(arr) :

    // If the array length + 1 of the accumulator is smaller than the array length of the original array concatenate the array element at index i else... 
    acc.length + 1 < arr.length ? removeItemPrep(acc.concat(arr[i]))(i + 1)(idx)(arr) : 

    // return the accumulator
    acc 

const removeItem = removeItemPrep([])(0)

const array = [1, 2, 3]
const index = 1

const newArray = removeItem(index)(array) 

console.log(newArray) // logs the following array to the console : [1, 3]

虽然大多数先前的答复都回答了这个问题,但是为什么没有使用切片()方法还不够清楚。 是的,过滤器()符合不可改变的标准,但做以下更短的等值如何?

const myArray = [1,2,3,4];

现在让我们说我们应该从阵列中删除第二个元素, 我们可以简单地做到:

const newArray = myArray.slice(0, 1).concat(myArray.slice(2, 4));

// [1,3,4]

今天,社区强烈鼓励从阵列中删除元素,因为其简单和不可改变的性质。 一般来说, 导致突变的方法应该避免。 例如, 鼓励您将推( ) 替换为 concat () , 并用切片 () 替换为 plus () 。

以下方法将从数组中删除给定值的所有条目, 不创建新数组, 并且只有一个超快的迭代。 它在古老的 Internet Explorer 5. 5 浏览器中有效 :

{( var i = 0, k = 0, 2, 0, 0, 3); 文档. gettlementByld ('code'). innerHTML = 初始阵列 [“+ a.join (), ']+']; // 初始阵列 [0. 1, 0, 2, 0, 3] 移除From Array (a) ; 文件. getElementById ('code'). innerHTML = “Intial 阵列 + a.join (', ') + ; /// Intial 阵列 [0, 0, 2, 0, 3] regall; 文件. getElementById ('code'). innerHTML = “ br> Resulting 阵列 [ + a.join (') + code]; / / = ascoard= 数 [1, 2, 3]

用于解决多个浏览器的问题。 如果存在的话, 它会使用在建浏览器的方法。 如果没有这些方法, 则使用自己的自定义方法。 如果像旧版的互联网探索者一样, 它会使用自己的自定义方法 。

从数组中删除元素( 从网站) 的简单示例 :

_.without([1, 2, 1, 0, 3, 1, 4], 0, 1); // => [2, 3, 4]