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

array.remove(value);

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


当前回答

您永远不应该根据功能性编程模式改变您的阵列。 您可以创建一个新的阵列, 而不引用您想要更改的数据 ECMAScript 6 方法 。filter;

var myArray = [1, 2, 3, 4, 5, 6];

假设您想要删除5从数组中,您可以简单地这样做:

myArray = myArray.filter(value => value !== 5);

这将给您一个没有您想要删除的值的新数组。 因此结果将是 :

 [1, 2, 3, 4, 6]; // 5 has been removed from this array

关于进一步理解,请阅读MDN文件:Array.过滤器.

其他回答

OK,OK, OK, OK, OK, OK, OK, OK, OK,OK, OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,OK,例如,您有下面的数组:

var num = [1, 2, 3, 4, 5];

我们想要删除第4号, 你可以简单地使用下面的代码:

num.splice(num.indexOf(4), 1); // num will be [1, 2, 3, 5];

如果您正在重复使用此函数,请写入一个可重复使用的函数,该函数将附于原土类似以下的数组函数 :

Array.prototype.remove = Array.prototype.remove || function(x) {
  const i = this.indexOf(x);
  if(i===-1)
      return;
  this.splice(i, 1); // num.remove(5) === [1, 2, 3];
}

但如果您有下面的数组, 而不是数组中的几个 [5] 呢?

var num = [5, 6, 5, 4, 5, 1, 5];

我们需要一个循环来检查它们, 但是一个更容易和更有效的方法是使用内置的 JavaScript 函数, 所以我们写一个函数, 使用下面这样的过滤器 :

const _removeValue = (arr, x) => arr.filter(n => n!==x);
//_removeValue([1, 2, 3, 4, 5, 5, 6, 5], 5) // Return [1, 2, 3, 4, 6]

还有第三方图书馆,如Lodash 或Goint, 也帮助你这样做。更多信息,请参看 Lodash _. pull,_. pullAt 或_。

 (function removeFromArrayPolyfill() {
      if (window.Array.prototype.remove) return;
    
      Array.prototype.remove = function (value) {
        if (!this.length || !value) return;
    
        const indexOfValue = this.indexOf(value);
    
        if (indexOfValue >= 0) {
          this.splice(indexOfValue, 1);
        }
      };
    })();
    
    // testing polyfill
    const nums = [10, 20, 30];
    nums.remove(20);
    console.log(nums);//[10,30]

例如,您有一个字符数组,想要从数组中删除“A”。

数组有一个过滤方法,可以过滤并只返回您想要的元素。

let CharacterArray = ['N', 'B', 'A'];

我想返回元素 除了"A"。

CharacterArray = CharacterArray.filter(character => character !== 'A');

字符阵列必须是 : ['N', 'B']

我喜欢这个单行道:

arr.includes(val) && arr.splice(arr.indexOf(val), 1)
  • 欧 6(无 (没有) (没有) (没有) (没有)Internet 探索器支助))
  • 在原地清除。
  • 快速: 不重复重复重复或重复 。
  • 支持删除这些值nullundefined

作为原型

// remove by value. return true if value found and removed, false otherwise
Array.prototype.remove = function(val)
{
    return this.includes(val) && !!this.splice(this.indexOf(val), 1);
}

(是的,我读了所有其他的答案 却找不到一个结合的答案)includessplice在同一行中。 )

很简单,只要做:

var arr = [1,2,4,5];
arr.splice(arr.indexOf(5), 1);
console.log(arr); // [1,2,4];