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

array.remove(value);

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


当前回答

通常比较好用过滤功能创建新阵列。

let array = [1,2,3,4];
array = array.filter(i => i !== 4); // [1,2,3]

这还提高了易读性IMHO。我不是切片的粉丝, 虽然它知道有时你应该去。

其他回答

let removeAnElement = (arr, element)=>{
    let findIndex = -1;
    for (let i = 0; i<(arr.length); i++){
        if(arr[i] === element){
            findIndex = i;
            break;
        }
    }
    if(findIndex == -1){
        return arr;
    }
    for (let i = findIndex; i<(arr.length-1); i++){
        arr[i] =  arr[i+1];
    }
    arr.length -= 1;
    return arr;
}

let array = ['apple', 'ball', 'cat', 'dog', 'egg'];
let removeElement = 'ball';

let tempArr2 = removeAnElement(array, 'dummy');
console.log(tempArr2);
// ['apple', 'cat', 'dog', 'egg']

let tempArr = removeAnElement(array, removeElement);
console.log(tempArr);`enter code here`
// ['apple', 'cat', 'dog', 'egg']

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

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

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

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

这提供了一个前提值, 而不是一个值 。

注:它将更新给定阵列,并返回受影响的行。

用法

var removed = helper.remove(arr, row => row.id === 5 );

var removed = helper.removeAll(arr, row => row.name.startsWith('BMW'));

定义定义定义定义定义的定义定义定义定义定义的定义定义定义定义定义的定义定义定义定义定义定义的定义

var helper = {
 // Remove and return the first occurrence

 remove: function(array, predicate) {
  for (var i = 0; i < array.length; i++) {
   if (predicate(array[i])) {
    return array.splice(i, 1);
   }
  }
 },

 // Remove and return all occurrences

 removeAll: function(array, predicate) {
  var removed = [];

  for (var i = 0; i < array.length; ) {
   if (predicate(array[i])) {
    removed.push(array.splice(i, 1));
    continue;
   }
   i++;
  }
  return removed;
 },
};

根据所有主要正确的答复并考虑到建议的最佳做法(特别是不直接使用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 比较, 以防浏览器支持地图, 它比 Lodash 还要快! 注意我没有使用 Array. prototype. indexof 或 Array. prototype 。 包含在地图或天体中将ExcludeValue 包装成快的查询 !

我不知道你如何期待阵列.remove( int) 的行为。 我可以想到三种可能性, 你可能会想要。

要删除索引 i 中的数组元素:

array.splice(i, 1);

如果您想要从数组中删除带有数值数的每个元素 :

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

如果您只想在索引 I 中使元素不再存在, 但是您不想让其它元素的索引改变 :

delete array[i];