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

array.remove(value);

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


当前回答

Array.prototype.removeByValue = function (val) {
  for (var i = 0; i < this.length; i++) {
    if (this[i] === val) {
      this.splice(i, 1);
      i--;
    }
  }
  return this;
}

var fruits = ['apple', 'banana', 'carrot', 'orange'];
fruits.removeByValue('banana');

console.log(fruits);
// -> ['apple', 'carrot', 'orange']

其他回答

我想根据ECMAScript 6。假设您拥有如下阵列:

let arr = [1,2,3,4];

如果您想要在特殊索引中删除2,写下以下代码:

arr.splice(2, 1); //=> arr became [1,2,4]

但是,如果你想删除一个特殊项目,比如3并且你不知道它的索引, 做如下:

arr = arr.filter(e => e !== 3); //=> arr became [1,2,4]

提示提示:请使用箭头函数进行过滤回击,除非您得到空数组。

您只需要按元素或索引过滤 :

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

var result1 = num.filter((el, index) => el != 5) // for remove all 5
var result2 = num.filter((el, index) => index != 5) // for remove item with index == 5

console.log(result1);
console.log(result2);

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

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

创建新阵列 :

var my_array = new Array();

添加元素到此数组 :

my_array.push("element1");

函数索引of (返回指数或 -1 未找到时) :

var indexOf = function(needle)
{
    if (typeof Array.prototype.indexOf === 'function') // Newer browsers
    {
        indexOf = Array.prototype.indexOf;
    }
    else // Older browsers
    {
        indexOf = function(needle)
        {
            var index = -1;

            for (var i = 0; i < this.length; i++)
            {
                if (this[i] === needle)
                {
                    index = i;
                    break;
                }
            }
            return index;
        };
    }

    return indexOf.call(this, needle);
};

检查此元素的索引( 使用 Firefox 和 Internet Explorer 8 (及以后) 测试) :

var index = indexOf.call(my_array, "element1");

从数组中删除位于索引处的 1 元素

my_array.splice(index, 1);

您可以在 JavaScript 以多种方式完成此任务

  1. 如果您知道该值的索引:在此情况下,您可以使用复数

    var arr = [1,2,3,4]
    // Let's say we have the index, coming from some API
    let index = 2;
    // splice is a destructive method and modifies the original array
    arr.splice(2, 1)
    
  2. 如果您没有索引, 并且只有数值: 在此情况下, 您可以使用过滤器

    // Let's remove '2', for example
    arr = arr.filter((value)=>{
        return value !== 2;
    })