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

array.remove(value);

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


当前回答

我认为许多 JavaScript 指令对于功能性编程没有很好的想法。 Splice 返回被删除的元素, 大部分时间您需要减少的数组。 这是不好的 。

想象一下您正在做一个循环调用, 并且不得不通过一个阵列, 并用一个更少的项目, 可能没有当前索引化的项目 。 或者想象一下您正在做另一个循环调用, 并且不得不通过一个带有元素推动的阵列 。

在这两种情况中,你都不能做我的递归功能(myArr.push(c))或我的递归功能(myArr.spice(i,1) ) 。 第一个白痴实际上会通过阵列的长度,第二个白痴会通过删除的元素作为参数。

所以事实上我所做的是... :删除一个阵列元素, 并将结果传递到一个参数的函数中, 同时我做如下:

myRecursiveFunction(myArr.slice(0,i).concat(a.slice(i+1)))

说到推,那更傻...

myRecursiveFunction((myArr.push(c),myArr))

我相信一种正确的功能语言 一种方法突变它所呼吁的物体 就必须返回一个引用 作为结果的物体本身。

其他回答

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

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

您可以从数组中添加一个原型函数来“ 移除” 元素 。

以下示例显示当我们知道一个元素的索引时, 如何简单地从数组中删除一个元素。 我们用它来使用 Array. filter 方法 。

Array. prototype. removeByIndex = 函数 (i) {如果 (! Number. is Integer(i) {i < 0) {/ i 必须是一个整数返回它;} 返回此. filter( f, indx) { indx! = i)} var a = [5, - 89, 2 * 2, " some string", null, froid, 未定义, 20, null, 5]; var b = a. remove ByIndex(2); control.log(a); control.log(b);

有时候我们不知道元素的索引

Array. prototype. remove = 函数 (i) { 返回此. filter (f \ \ f \ f y = i) {var a = [5, - 89, 2 ( 2 * 2), “ 一些字符串 ” 无效, 错误, 未定义, 20, 无效, 5] ; var b = a. remove(5). remove (null); 控制台. log (a); 控制台. log (b) / 它消除了所有搜索值的发生次数 。

但是,当我们只想要删除搜索值的首次出现时, 我们可以在函数中使用 Array. indexof 方法 。

Array. prototype. removeFirst = 函数 (i) {i = this.indexof (i); if (! Number. is Integer (i) {i < 0) {返回此 ;} 返回此. filter (f, indx) { indx = indx ! = i)} var a = [5, - 89, 2 * 2, " some string", null, fraud, 未定义, 20, null, 5]; var b = a.remove First(5).remove First(nell); translavor.log(a) ; controad.log(b);

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

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

然后:

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

弹出 :

[1, 2, 4]

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

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

我本人也有这个问题(在更换阵列是可以接受的情况下),

var filteredItems = this.items.filter(function (i) {
    return i !== item;
});

要给上面的片段略加上下文:

self.thingWithItems = {
    items: [],
    removeItem: function (item) {
        var filteredItems = this.items.filter(function (i) {
            return i !== item;
        });

        this.items = filteredItems;
    }
};

此解决方案应该同时使用引用项和值项。 它都取决于您是否需要保持对原始数组的引用, 以判断该解决方案是否适用 。