如何从数组中删除一个特定值? 类似 :
array.remove(value);
制约:我必须使用核心 JavaScript 。 框架不允许 。
如何从数组中删除一个特定值? 类似 :
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]
其他回答
您可以扩展数组对象以定义自定义的删除函数如下:
let let = [1, 2,4,4,4,5,5,45,9;] 数.delete = 函数(价值) { var indexof Target = this.indexof (value) =.indexof(value) = this.if(indexoftaget = = = = = = = = = = y= = y,4,4,4,5,4,459; 数. 数.delet = 函数(val = val indexof Talget = this. indexeof(valent) = = = = = indexget =.indexof = = =. { = indexexuf(val =) { = = indexete = = / / / imme eleteletelete (1) // / / / / 预期输出= / / / tradestrayf delett 删除 2,4,4,4,4,4,4,5,5,5,4,4,5,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,9/ /
删除上次发生或所有发生, 还是第一次发生 ?
var array = [2, 5, 9, 5];
// Remove last occurrence (or all occurrences)
for (var i = array.length; i--;) {
if (array[i] === 5) {
array.splice(i, 1);
break; // Remove this line to remove all occurrences
}
}
或
var array = [2, 5, 9, 5];
// Remove first occurrence
for (var i = 0; array.length; i++) {
if (array[i] === 5) {
array.splice(i, 1);
break; // Do not remove this line
}
}
更现代的ECMAScript 2015(原称和谐或ES6)方法。
const items = [1, 2, 3, 4];
const index = 2;
然后:
items.filter((x, i) => i !== index);
弹出 :
[1, 2, 4]
您可以使用 Babel 和多填充服务,以确保浏览器之间有很好的支持。
如果元素存在多个实例,您可以进行后回循环,以确保不破坏索引。
var myElement = "chocolate"; var my Array = [“cocolate ”、“potart”、“potart”、“potart”、“potart”、“cocolate”、“potart”、“potart”、“cococolate ”]; / * 重要代码 * / 用于 (var i = my Array. lary - 1; i & 0; i-) {如果 (my Array [i] = my Element) my Array.spolice (i, 1);}控制台.log (my Array); {如果 (my Array [i] = my Element) my Array.splice (i, 1);} 控制台(my Array);
咖啡:
my_array.splice(idx, 1) for ele, idx in my_array when ele is this_value