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

array.remove(value);

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


当前回答

最基本的解决办法是:

array.key = null;

其他回答

 const Delete = (id) => {
      console.log(id)
     var index = Array.map(function(e){
      return e.id;
     
     }).indexOf(id);
     Array.splice(index,1);
     
}
    Array.prototype.remove = function(start, end) {
        var n = this.slice((end || start) + 1 || this.length);
        return this.length = start < 0 ? this.length + start : start,
        this.push.apply(this, n)
    }

startend可以是负数。在这种情况下,它们会从数组的末尾计数。

如果只有start中指定,只删除一个元素。

函数返回新数组长度。

z = [0,1,2,3,4,5,6,7,8,9];

newlength = z.remove(2,6);

(8) [0, 1, 7, 8, 9]

z=[0,1,2,3,4,5,6,7,8,9];

newlength = z.remove(-4,-2);

(7) [0, 1, 2, 3, 4, 5, 9]

z=[0,1,2,3,4,5,6,7,8,9];

newlength = z.remove(3,-2);

(4) [0, 1, 2, 9]

使用 jQuery 的阵列 :

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

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

虽然大多数前一个答复都回答了问题,但现在还不清楚为什么slice()未使用方法。是的,filter()符合不可改变标准,但采用以下较短的等值方法如何?

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

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

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

// [1,3,4]

以这种方式从一个阵列中删除元素的方式, 今天社区强烈鼓励从一个阵列中删除元素, 因为它的简单和不可改变的性质。 一般而言, 导致突变的方法应该避免。 例如, 鼓励您替换push()concat()splice()slice().

Array.prototype.removeByValue = function (val) {
  for (var i = 0; i < this.length; i++) {
    if (this[i] === val) {
      this.splice(i, 1);
      i--;
    }
  }
  return this;
}

var fruits = ['apple', 'banana', 'carrot', 'orange'];
fruits.removeByValue('banana');

console.log(fruits);
// -> ['apple', 'carrot', 'orange']