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

array.remove(value);

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


当前回答

  1. 使用 indexof, 能找到来自数组的具体数字索引
    • 使用 spplice, 可以从数组中删除特定的索引 。

const array = [1,2,3,4,5,6,7,8,9,0];
const index = array.indexOf(5);
// find Index of specific number
if(index != -1){
    array.splice(index, 1); // remove number using index
}
console.log(array);

  1. 删除全部事件 。 @ info: whatsthis

let array = [1, 2, 3, 4, 5, 1, 7, 8, 9, 2, 3, 4, 5, 6];
array = array.filter(number=> number !== 5);
console.log(array);

  1. 使用合并和拆分

    let array = [1, 2, 3, 4, 5, 1, 7, 8, 9, 2, 3, 4, 5, 6]
    array = Array.from(array.join("-").split("-5-").join("-").split("-"),Number)
    console.log(array)

其他回答

通过传递其值来删除项目 --

const remove=(value)=>{
    myArray = myArray.filter(element=>element !=value);

}

将项目通过索引编号删除 -

  const removeFrom=(index)=>{
    myArray = myArray.filter((_, i)=>{
        return i!==index
    })
}

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

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

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

查找index使用indexOf,然后删除该索引splice.

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

const array = [2, 5, 9];

console.log(array);

const index = array.indexOf(5);
if (index > -1) { // only splice array when item is found
  array.splice(index, 1); // 2nd parameter means remove one item only
}

// array = [2, 9]
console.log(array); 

第二个参数的第二个参数splice是要删除的元素数。请注意splice修改现有数组,并返回含有已删除元素的新数组。


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

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))

在类型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;
}

我不知道你是怎么想的array.remove(int)行为。我可以想到三种可能性 你可能想要。

在索引中删除数组的元素i:

array.splice(i, 1);

如果您想要删除带有值的每个元素number从数组 :

for (var i = array.length - 1; i >= 0; i--) {
 if (array[i] === number) {
  array.splice(i, 1);
 }
}

如果您只想在索引中生成元素i不再存在,但你不希望其它元素的索引改变:

delete array[i];

我本人也有这个问题(在更换阵列是可以接受的情况下),

var filteredItems = this.items.filter(function (i) {
    return i !== item;
});

要给上面的片段略加上下文:

self.thingWithItems = {
    items: [],
    removeItem: function (item) {
        var filteredItems = this.items.filter(function (i) {
            return i !== item;
        });

        this.items = filteredItems;
    }
};

此解决方案应该同时使用引用项和值项。 它都取决于您是否需要保持对原始数组的引用, 以判断该解决方案是否适用 。