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

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)

其他回答

var array = [2, 5, 9];
var res = array.splice(array.findIndex(x => x==5), 1);

console.log(res)

使用 Array. findindindex, 我们可以减少代码行数。

开发者.mozilla.org

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

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]

此函数从特定位置的数组中删除元素。

array.remove(position);

Array.prototype.remove = function (pos) {
    this.splice(pos, 1);
}

var arr = ["a", "b", "c", "d", "e"];
arr.remove(2); // remove "c"
console.log(arr);

如果您不知道要删除的项目的位置, 请使用这个 :

array.erase(element);

Array.prototype.erase = function(el) {
    let p = this.indexOf(el); // indexOf use strict equality (===)
    if(p != -1) {
        this.splice(p, 1);
    }
}

var arr = ["a", "b", "c", "d", "e"];
arr.erase("c");
console.log(arr);

删除上次发生或所有发生, 还是第一次发生 ?

var array = [2, 5, 9, 5];

// Remove last occurrence (or all occurrences)
for (var i = array.length; i--;) {
  if (array[i] === 5) {
     array.splice(i, 1);
     break; // Remove this line to remove all occurrences
  }
}

var array = [2, 5, 9, 5];

// Remove first occurrence
for (var i = 0; array.length; i++) {
  if (array[i] === 5) {
     array.splice(i, 1);
     break; // Do not remove this line
  }
}

对我而言,越简单越好,2018年(2019年左右),我给你这个(近一点)单行话,回答最初的问题:

Array.prototype.remove = function (value) {
    return this.filter(f => f != value)
}

有用的是,你可以用在咖喱的表达方式上,比如:

[1,2,3].remove(2).sort()