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

array.remove(value);

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


当前回答

虽然大多数前一个答复都回答了问题,但现在还不清楚为什么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.removeItem = function(a) {
    for (i = 0; i < this.length; i++) {
        if (this[i] == a) {
            for (i2 = i; i2 < this.length - 1; i2++) {
                this[i2] = this[i2 + 1];
            }
            this.length = this.length - 1
            return;
        }
    }
}

var recentMovies = ['Iron Man', 'Batman', 'Superman', 'Spiderman'];
recentMovies.removeItem('Superman');

如果元素存在多个实例,您可以进行后回循环,以确保不破坏索引。

var myElement = "chocolate";
var myArray = ['chocolate', 'poptart', 'poptart', 'poptart', 'chocolate', 'poptart', 'poptart', 'chocolate'];

/* Important code */
for (var i = myArray.length - 1; i >= 0; i--) {
  if (myArray[i] == myElement) myArray.splice(i, 1);
}
console.log(myArray);

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']

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

console.log(res)

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

开发者.mozilla.org

Vanilla JavaScript(ES5.1) - (ES5.1) -已经到位版本版本

浏览器支持 :因特网探索者 9或以后(或以后(详细浏览器支持)

/**
 * Removes all occurences of the item from the array.
 *
 * Modifies the array “in place”, i.e. the array passed as an argument
 * is modified as opposed to creating a new array. Also returns the modified
 * array for your convenience.
 */
function removeInPlace(array, item) {
    var foundIndex, fromIndex;

    // Look for the item (the item can have multiple indices)
    fromIndex = array.length - 1;
    foundIndex = array.lastIndexOf(item, fromIndex);

    while (foundIndex !== -1) {
        // Remove the item (in place)
        array.splice(foundIndex, 1);

        // Bookkeeping
        fromIndex = foundIndex - 1;
        foundIndex = array.lastIndexOf(item, fromIndex);
    }

    // Return the modified array
    return array;
}

Vanilla JavaScript(ES5.1) - (ES5.1) -不可变版本版本

浏览器支持: 与原版的香草 JavaScript 相同

/**
 * Removes all occurences of the item from the array.
 *
 * Returns a new array with all the items of the original array except
 * the specified item.
 */
function remove(array, item) {
    var arrayCopy;

    arrayCopy = array.slice();

    return removeInPlace(arrayCopy, item);
}

香草ES6 -不可变版本版本

浏览器支持: Chrome 46, 边缘 12, Firefox 16, Opera 37, Safari 8 ()详细浏览器支持)

/**
 * Removes all occurences of the item from the array.
 *
 * Returns a new array with all the items of the original array except
 * the specified item.
 */
function remove(array, item) {
    // Copy the array
    array = [...array];

    // Look for the item (the item can have multiple indices)
    let fromIndex = array.length - 1;
    let foundIndex = array.lastIndexOf(item, fromIndex);

    while (foundIndex !== -1) {
        // Remove the item by generating a new array without it
        array = [
            ...array.slice(0, foundIndex),
            ...array.slice(foundIndex + 1),
        ];

        // Bookkeeping
        fromIndex = foundIndex - 1;
        foundIndex = array.lastIndexOf(item, fromIndex)
    }

    // Return the new array
    return array;
}