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

array.remove(value);

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


当前回答

我张贴我的代码,删除一个阵列元素, 并缩短阵列长度 。

function removeElement(idx, arr) {
    // Check the index value
    if (idx < 0 || idx >= arr.length) {
        return;
    }
    // Shift the elements
    for (var i = idx; i > 0; --i) {
        arr[i] = arr[i - 1];
    }
    // Remove the first element in array
    arr.shift();
}

其他回答

如果您在数组中有复杂的对象, 您可以使用过滤器 。 在 $. in Array 或 tray. splice 不容易使用的情况下 。 特别是如果对象在数组中可能是浅的 。

例如,如果您有一个带有 Id 字段的对象,而您想要从数组中删除该对象:

this.array = this.array.filter(function(element, i) {
    return element.id !== idToRemove;
});

我不知道你是怎么想的array.remove(int)行为。我可以想到三种可能性 你可能想要。

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

array.splice(i, 1);

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

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

如果您只想在索引中生成元素i不再存在,但你不希望其它元素的索引改变:

delete array[i];

创建新阵列 :

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

ES6且无突变:(2016年10月)

const removeByIndex = (list, index) =>
      [
        ...list.slice(0, index),
        ...list.slice(index + 1)
      ];
         
output = removeByIndex([33,22,11,44],1) //=> [33,11,44]
      
console.log(output)

我测试过splicefilter查看哪个速度更快 :

let someArr = [...Array(99999).keys()] 

console.time('filter')
someArr.filter(x => x !== 6666)
console.timeEnd('filter')

console.time('splice by indexOf')
someArr.splice(someArr.indexOf(6666), 1)
console.timeEnd('splice by indexOf')

在我的机器上splice更快。这有道理,因为splice仅编辑现有的数组,而filter创建新数组。

尽管如此,filter逻辑上更清洁(容易阅读),更适合使用不可改变状态的编码风格。所以由你决定是否进行这种权衡决定。