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

array.remove(value);

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


当前回答

如果元素存在多个实例,您可以进行后回循环,以确保不破坏索引。

var myElement = "chocolate";
var myArray = ['chocolate', 'poptart', 'poptart', 'poptart', 'chocolate', 'poptart', 'poptart', 'chocolate'];

/* Important code */
for (var i = myArray.length - 1; i >= 0; i--) {
  if (myArray[i] == myElement) myArray.splice(i, 1);
}
console.log(myArray);

其他回答

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

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

let array = [5,5,4,4,2,3,4]    
let newArray = array.join(',').replace('5','').split(',')

如果您想要删除一个当前项目, 此示例将有效 。

对我而言,越简单越好,2018年(2019年左右),我给你这个(近一点)单行话,回答最初的问题:

Array.prototype.remove = function (value) {
    return this.filter(f => f != value)
}

有用的是,你可以用在咖喱的表达方式上,比如:

[1,2,3].remove(2).sort()

你的问题没有说明顺序或不同的价值是否是一项要求。

如果您不关心顺序, 并且容器中的值不会超过一次, 请使用“ Set ” 。 它会更快, 更简洁 。

var aSet = new Set();

aSet.add(1);
aSet.add(2);
aSet.add(3);

aSet.delete(2);

您在数组中有 1 到 9 个, 您想要删除 5 个 。 请使用以下代码 :

var numberArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];

var newNumberArray = numberArray.filter(m => {
  return m !== 5;
});

console.log("new Array, 5 removed", newNumberArray);


如果您想要多个值。例如:- 1,7,8

var numberArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];

var newNumberArray = numberArray.filter(m => {
  return (m !== 1) && (m !== 7) && (m !== 8);
});

console.log("new Array, 1,7 and 8 removed", newNumberArray);


如果您想要删除数组中的数组值。 例如 : [3,4,5]

var numberArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];
var removebleArray = [3,4,5];

var newNumberArray = numberArray.filter(m => {
    return !removebleArray.includes(m);
});

console.log("new Array, [3,4,5] removed", newNumberArray);

包括支持的浏览器链接链接.