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

array.remove(value);

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


当前回答

更新: 只有当您无法使用 ECMAScript 2015 (前称ES6) 时, 才会推荐使用此方法。 如果您可以使用此方法, 其它答案可以提供更清晰的落实 。


此条格将解决您的问题, 并删除所有参数, 而不是仅一个( 或指定值 ) 。

Array.prototype.destroy = function(obj){
    // Return null if no objects were found and removed
    var destroyed = null;

    for(var i = 0; i < this.length; i++){

        // Use while-loop to find adjacent equal objects
        while(this[i] === obj){

            // Remove this[i] and store it within destroyed
            destroyed = this.splice(i, 1)[0];
        }
    }

    return destroyed;
}

用法 :

var x = [1, 2, 3, 3, true, false, undefined, false];

x.destroy(3);         // => 3
x.destroy(false);     // => false
x;                    // => [1, 2, true, undefined]

x.destroy(true);      // => true
x.destroy(undefined); // => undefined
x;                    // => [1, 2]

x.destroy(3);         // => null
x;                    // => [1, 2]

其他回答

删除在索引i 上的元素, 不突变原始数组 :

/**
* removeElement
* @param {Array} array
* @param {Number} index
*/
function removeElement(array, index) {
   return Array.from(array).splice(index, 1);
}

// Another way is
function removeElement(array, index) {
   return array.slice(0).splice(index, 1);
}

尝试使用过滤器方法使用此代码, 您可以从数组中删除任何特定项 。

let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
function removeItem(arr, value) {
  return arr.filter(function (ele) {
    return ele !== value;
  });
}
console.log(removeItem(arr, 6));

spolice () 函数能够将数组中的项目还给您, 从特定的索引中删除项目 / 项 :

函数删除 ArrayText( index, 数组) { 数组. splice( index, 1); 返回数组; } 让数组 = [ 1, 2, 3,4]; 让 index = 2; 数组 = 删除 ArrayText( index, 数组); 控制台. log( 数组);

此函数从特定位置的数组中删除元素。

数组. remove( 位置) ;

Array. prototype. remove = 函数 (pos) {此. splice(pos, 1);} var arr = ["a", "b", "c", "d", "e"]; arr. remove(2); // 移除"c" 控制台.log(ar);

如果您不知道要删除的项目的位置, 请使用这个 :

array.erase(element);

Array. prototype. erase = 函数( el) { let p = this. indexof (el); // indexof use prettical equality () { this. spliice (p, 1);}} var ar ar = ["a", "b", "c", "d", "e"; arr.erase (c"); 控制台. log (a) ;

从数组中删除一个特定元素, 可以在过滤器选项的一行内完成, 它得到所有浏览器的支持 : https:// caniuse. com/ #search=filter% 20arary

function removeValueFromArray(array, value) {
    return array.filter(e => e != value)
}

我在这里测试了此函数 : https://bit.dev/joshk/jotils/remove-value- from-array/~code#test.ts