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

array.remove(value);

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


当前回答

使用 JavaScript 从数组中删除一个项的几种方法 。

所描述的所有方法都不改变原始数组,而是创建一个新的数组。

如果您知道某个项目的索引

假设您有一个阵列, 您想要删除位置 i 上的项目 。

一种方法是使用切片( ) :

const items = [a], 'b','c','d','e','f'] const i = 3 const 过滤项目 = items.selice(0, i).concat( items.selice( i+1, items. long)) 控制台.log( 过滤项目)

切片 () 创建新数组, 使用它收到的索引 。 我们只需创建一个新数组, 从开始到要删除的索引, 并且将另一个数组从我们删除后的第一个位置集中到数组的末尾 。

如果您知道数值

在这种情况下,一个很好的选择是使用过滤器(),这提供了一种更宣示性的方法:

Const 项 = [“ a ”、“ b ” 、 “ c ” 、 “ d ” 、 “ e ” 、 “ f ” 、 “ f ” 等值 Toremove = “ c” 等式过滤项目 = 项. filter (项目 项 ! ! ! = ex 值 to remove) 控制台.log (过滤项目 )

此选项使用 ES6 箭头函数。 您可以使用传统函数支持旧的浏览器 :

const items = ['a', 'b','c','d','d','e','f'] const value to remove ='c' const 过滤项目= items. filter(功能(项目) {返回项目!}== value to remove}控制台.log(过滤项目)

或者你可以使用 Babel 将ES6代码转换回ES5, 使旧浏览器更容易消化, 而在您的代码中写入现代 JavaScript 。

删除多个项目

如果不是单项,而是要删除许多项,会怎么样?

让我们找到最简单的解决方案

按指数分列的指数

您可以在序列中创建函数并删除项目 :

const items = [a], b', c', d', d', e', e', e', f'] const demote =( items, i) = items = (items, i, i' i) {{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{}}}}}} {{{{{{{{{{{{{{{{{{{{}}}}}} {{{{{{{{{{{{{{}}}{{{{{{{{{{{{{{}}}}{{{{{{{{{{{{{{{{{{{}}}} {{{{{{{{{{{{{}}}}}{{{{{{{{}}}}}}}{{{{{{{{}}}}}}{{{{{{{{{{{{}}}}}}}}}}}{{{{{{{{{}}}}}}}}}}}}}}}{{{{{}}}}}}}{{}}}}{{{{{}}}}}{{{{{}}}}}}}}}{{{{{{{{{{{{{{{{}}}}}{{{{{{{{{{}}}}}}}}{{{{}}}}{{{{{{{{{{}}}}{}}}}}}}}}{}}}}}}}}}}}}}}}}}}{}}}}}}}}}}}{{}{{}{}{}}}}{{}}}}}}}}}}{}{}{}

以数值计

您可以在回溯函数中搜索包含内容 :

const items = ['a', 'b', 'c','d','d','e','f'] const value to remove = ['c','d'] comst filtems = items. filter(项目 \\\ ? $values to remove.) 包括(项目) // ["a","b","e","f" 控制台。log(过滤项目)

避免突变原始数组

plice() spolice () (不得与切片() 相混淆) 使原始数组变形, 并应避免 。

(最初张贴在我的网站上:https://flaviocopes.com/how-to-remove-itm-from-array/)

其他回答

更现代的ECMAScript 2015(原称和谐或ES6)方法。

const items = [1, 2, 3, 4];
const index = 2;

然后:

items.filter((x, i) => i !== index);

弹出 :

[1, 2, 4]

您可以使用 Babel 和多填充服务,以确保浏览器之间有很好的支持。

检查一下这个代码 每个主要浏览器都使用这个代码

删除项目 = 函数( rr) { varb = ' ; 对于 (b in arr) { 如果 (ar[ b] { { { { { rr. splice( b, 1); 折断 ; } rr; } 返回 arr; } } 返回 arr; } ; var 数组 = [1, 5,6, 9, 5, 5, 355] var res = mote_ item( arry, 5); 控制台. log( res) = [1, 3, 5, 9, 5, 5, 55, Var Res = dection_ item( arry, 5); 控制台 log( res)

如果您想要删除删除位置的新数组, 您总是可以删除特定元素并过滤数组。 它可能需要为不执行过滤方法的浏览器扩展数组对象, 但从长远来看, 它比较容易, 因为您所做的只是:

var my_array = [1, 2, 3, 4, 5, 6];
delete my_array[4];
console.log(my_array.filter(function(a){return typeof a !== 'undefined';}));

它应显示[1、2、3、4、6]。

根据所有主要正确的答复并考虑到建议的最佳做法(特别是不直接使用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 包装成快的查询 !

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');