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

array.remove(value);

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


当前回答

var array = [2, 5, 9];
var res = array.splice(array.findIndex(x => x==5), 1);

console.log(res)

使用 Array. findindindex, 我们可以减少代码行数。

开发者.mozilla.org

其他回答

我找到了这个博客文章,

9 从 JavaScript 阵列中删除元素的方法 - 附加如何安全清除 JavaScript 阵列

我更喜欢用filter():

var filtered_arr = arr.filter(function(ele){
   return ele != value;
})

从字符串阵列中查找和删除一个特定的字符串:

var colors = ["red","blue","car","green"];
var carIndex = colors.indexOf("car"); // Get "car" index
// Remove car from the colors array
colors.splice(carIndex, 1); // colors = ["red", "blue", "green"]

资料来源:https://www.codegrepper.com/?search_term=remove+a+particular+element+from+array

尝试使用删除运算符

例如:

const arr = [10, 20, 30, 40, 50, 60];
delete arr[2]; // It will Delete element present at index 2
console.log( arr ); // [10, 20, undefined , 40, 50, 60]

注:使用删除运算符将会在数组中留下空空空/ 空洞。 它不会提醒数组的长度。 要在元素被删除时更改数组的长度, 请使用复数法 。

希望这能解决你所有的问题

更新 :只有当您无法使用 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]

这里有很多奇妙的答案, 但对我来说,最有效的答案 不是完全从阵列中移除我的元素, 而是简单地设定它的价值为无效。

这对大多数情况都有效,而且是一个很好的解决方案,因为我稍后会使用变量,而不想让变量消失,只是暂时空的。此外,这个方法完全可以交叉浏览。

array.key = null;