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

array.remove(value);

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


当前回答

根据所有主要正确的答复并考虑到建议的最佳做法(特别是不直接使用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.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);

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

您可以扩展数组对象以定义自定义的删除函数如下:

let numbers = [1,2,4,4,5,3,45,9];

numbers.delete = function(value){
    var indexOfTarget = this.indexOf(value)

    if(indexOfTarget !== -1)
    {
        console.log("array before delete " + this)
        this.splice(indexOfTarget, 1)
        console.log("array after delete " + this)
    }
    else{
        console.error("element " + value + " not found")
    }
}
numbers.delete(888)
// Expected output:
// element 888 not found
numbers.delete(1)

// Expected output;
// array before delete 1,2,4,4,5,3,45,9
// array after delete 2,4,4,5,3,45,9

你的问题没有说明顺序或不同的价值是否是一项要求。

如果您不关心顺序, 并且容器中的值不会超过一次, 请使用“ Set ” 。 它会更快, 更简洁 。

var aSet = new Set();

aSet.add(1);
aSet.add(2);
aSet.add(3);

aSet.delete(2);

答案已经很多了, 但是因为还没有人用一个衬里来做, 我想我会展示我的方法。 它会利用字符串. split () 函数在创建数组时将删除所有指定字符这一事实。 这里举一个例子 :

var ary = [1,2,3,4,1234,10,4,5,7,3];
out = ary.join("-").split("-4-").join("-").split("-");
console.log(out);

在此示例中, 所有 4 个的字符都在从数组中移除 。 但是, 必须指出, 包含字符“ - ” 的任何数组都会与此示例产生问题 。 简而言之, 这会导致组合( “ - ” ) 函数不适当地将您的字符串拼凑在一起。 在这种情况下, 上面的扇形中的所有“ - ” 字符串都可以替换为在原始数组中不会使用的任何字符串 。 以下还有一个示例 :

var ary = [1,2,3,4,'-',1234,10,'-',4,5,7,3];
out = ary.join("!@#").split("!@#4!@#").join("!@#").split("!@#");
console.log(out);