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

array.remove(value);

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


当前回答

我张贴我的代码,删除一个阵列元素, 并缩短阵列长度 。

function removeElement(idx, arr) {
    // Check the index value
    if (idx < 0 || idx >= arr.length) {
        return;
    }
    // Shift the elements
    for (var i = idx; i > 0; --i) {
        arr[i] = arr[i - 1];
    }
    // Remove the first element in array
    arr.shift();
}

其他回答

答案已经很多了, 但是因为还没有人用一个衬里来做, 我想我会展示我的方法。 它会利用字符串. split () 函数在创建数组时将删除所有指定字符这一事实。 这里举一个例子 :

var ary = [1、2、3、4、1234、10、4、5、7、3]; out = arry.join (" -" -").split ("-4 -").join (" -").split (" -").split (" -");control.log(out) ;

在此示例中, 所有 4 个的字符都在从数组中移除 。 但是, 必须指出, 包含字符“ - ” 的任何数组都会与此示例产生问题 。 简而言之, 这会导致组合( “ - ” ) 函数不适当地将您的字符串拼凑在一起。 在这种情况下, 上面的扇形中的所有“ - ” 字符串都可以替换为在原始数组中不会使用的任何字符串 。 以下还有一个示例 :

var ary = [1,2,3,4,'-',1234,10,'-',4,5,7,3]; out = ary.join("!@#").split("!@#4!@#").join("!@#").split("!@#"); console.log(out);

最干净的:

var arr = ['1','2','3']; arr = arr.filter (e'e? e?=======================================================================================================================================================3'3'); 控制台.warn(arr);

这也将删除重复(如果有的话)。

var index,
    input = [1,2,3],
    indexToRemove = 1;
    integers = [];

for (index in input) {
    if (input.hasOwnProperty(index)) {
        if (index !== indexToRemove) {
            integers.push(result); 
        }
    }
}
input = integers;

此解决方案将需要一系列输入, 并将通过输入查找要删除的值。 这将在整个输入数组中循环, 结果将是第二个已经删除了特定索引的数组整数组。 然后将整数组复制到输入数组中 。

使用 indexof 查找要删除的数组元素的索引,然后用复数删除该索引。

组合法通过删除现有元素和/或添加新元素来改变数组的内容。

const 数组 = [2, 5, 9] ; 控制台. log( 数组); const 指数 = 数组. indexof (5); 如果 (index > - 1) {/ / 仅当发现项目时 复数组 。 spice (index, 1) ; / 2nd 参数意味着只删除一个项 } // 数组 = [2, 9] 控制台. log( 数组) ;

复数的第二个参数是要删除的元素数量。 请注意, 复数会修改所在的数组, 并返回包含已删除元素的新数组 。


由于完整性的原因,此处为函数。第一个函数只删除一个单一事件(即从 [2,5,9,1,5,5,8,5] 中删除第一个匹配5),而第二个函数删除所有事件:

{ var indexof( val值); 如果 (index > - 1 ) { rr. spice( index, 1); } 返回 arr; } 函数删除TroitAll( arr, val值 = 0); { (i) < arr. long) { (arr) {( i) { rr. spice( i, 1); { other { +gi; } } 返回 arr; } / 使用控制台. log( removeteTunce ([ 2, 5, 9, 1, 5, 5, 5, 5 5 ) 控制台. log( removete TempallAll ( 2, 5, 9, 1, 5, 5, 5, 5) ) )

在类型Script中,这些函数可用类型参数保持类型安全:

function removeItem<T>(arr: Array<T>, value: T): Array<T> { 
  const index = arr.indexOf(value);
  if (index > -1) {
    arr.splice(index, 1);
  }
  return arr;
}

ES6且无突变:(2016年10月)

const removeByIndex = (list, index) => [ ...list.slice(0, index), ...list.slice(index + 1) ]; output = removeByIndex([33,22,11,44],1) //=> [33,11,44] console.log(output)