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

array.remove(value);

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


当前回答

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;
}

其他回答

根据所有主要正确的答复并考虑到建议的最佳做法(特别是不直接使用Array.prototype),我提出了以下代码:

function arrayWithout(arr, values) {
  var isArray = function(canBeArray) {
    if (Array.isArray) {
      return Array.isArray(canBeArray);
    }
    return Object.prototype.toString.call(canBeArray) === '[object Array]';
  };

  var excludedValues = (isArray(values)) ? values : [].slice.call(arguments, 1);
  var arrCopy = arr.slice(0);

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

  return arrCopy;
}

在审查上述功能时,尽管运作良好,但我意识到业绩可能有所改进。 使用ES6而不是ES5是一种更好的方法。

const arrayWithoutFastest = (() => {
  const isArray = canBeArray => ('isArray' in Array) 
    ? Array.isArray(canBeArray) 
    : Object.prototype.toString.call(canBeArray) === '[object Array]';

  let mapIncludes = (map, key) => map.has(key);
  let objectIncludes = (obj, key) => key in obj;
  let includes;

  function arrayWithoutFastest(arr, ...thisArgs) {
    let withoutValues = isArray(thisArgs[0]) ? thisArgs[0] : thisArgs;

    if (typeof Map !== 'undefined') {
      withoutValues = withoutValues.reduce((map, value) => map.set(value, value), new Map());
      includes = mapIncludes;
    } else {
      withoutValues = withoutValues.reduce((map, value) => { map[value] = value; return map; } , {}); 
      includes = objectIncludes;
    }

    const arrCopy = [];
    const length = arr.length;

    for (let i = 0; i < length; i++) {
      // If value is not in exclude list
      if (!includes(withoutValues, arr[i])) {
        arrCopy.push(arr[i]);
      }
    }

    return arrCopy;
  }

  return arrayWithoutFastest;  
})();

如何使用 :

const arr = [1,2,3,4,5,"name", false];

arrayWithoutFastest(arr, 1); // will return array [2,3,4,5,"name", false]
arrayWithoutFastest(arr, 'name'); // will return [2,3,4,5, false]
arrayWithoutFastest(arr, false); // will return [2,3,4,5]
arrayWithoutFastest(arr,[1,2]); // will return [3,4,5,"name", false];
arrayWithoutFastest(arr, {bar: "foo"}); // will return the same array (new copy)

我目前正在写博客文章, 其中我已设定数个无问题的阵列解决方案基准, 并比较运行时间。 一旦我完成此文章, 我将更新此答案, 并用链接更新。 仅供参考, 我比较了上述与没有 Lodash 的比较, 以防浏览器支持Map注意我没有用Array.prototype.indexOfArray.prototype.includes将exlcude Values 包装在MapObject让查询更快!

    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]

如果您必须支持旧版的 Internet Explorer 版本, 我建议使用以下多填充( 注意: 这是这是所有现代阵列方法(JavaScript 1.8.5/ECMAScript 5 Array Extras)的100%后向兼容的替代方法,这些方法适用于互联网探索者6+、Firefox 1.5+、Chrome、Safari和Opera。

https://github.com/plusdude/array-generics

您可以从数组中添加一个原型函数来“ 移除” 元素 。

以下示例显示当我们知道一个元素的索引时如何简单地从数组中删除一个元素。Array.filter方法。

Array.prototype.removeByIndex = function(i) {
    if(!Number.isInteger(i) || i < 0) {
        // i must be an integer
        return this;
    }

    return this.filter((f, indx) => indx !== i)
}
var a = [5, -89, (2 * 2), "some string", null, false, undefined, 20, null, 5];

var b = a.removeByIndex(2);
console.log(a);
console.log(b);

有时候我们不知道元素的索引

Array.prototype.remove = function(i) {
    return this.filter(f => f !== i)
}
var a = [5, -89, (2 * 2), "some string", null, false, undefined, 20, null, 5];

var b = a.remove(5).remove(null);
console.log(a);
console.log(b);

// It removes all occurrences of searched value

但是,当我们只想要删除搜索值的首次出现时,我们就可以使用Array.indexOf函数中的方法。

Array.prototype.removeFirst = function(i) {
    i = this.indexOf(i);

    if(!Number.isInteger(i) || i < 0) {
        return this;
    }

    return this.filter((f, indx) => indx !== i)
}
var a = [5, -89, (2 * 2), "some string", null, false, undefined, 20, null, 5];

var b = a.removeFirst(5).removeFirst(null);
console.log(a);
console.log(b);

使用数组过滤过滤器方法 :

let array = [1, 2, 3, 4, 511, 34, 511, 78, 88];

let value = 511;
array = array.filter(element => element !== value);
console.log(array)