如何从数组中删除一个特定值? 类似 :
array.remove(value);
我必须使用核心核心核心JavaScript。 不允许框架 。
如何从数组中删除一个特定值? 类似 :
array.remove(value);
我必须使用核心核心核心JavaScript。 不允许框架 。
当前回答
其他回答
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 my_array = [1, 2, 3, 4, 5, 6];
delete my_array[4];
console.log(my_array.filter(function(a){return typeof a !== 'undefined';}));
它应显示[1, 2, 3, 4, 6]
.
您只需要按元素或索引过滤 :
var num = [5, 6, 5, 4, 5, 1, 5];
var result1 = num.filter((el, index) => el != 5) // for remove all 5
var result2 = num.filter((el, index) => index != 5) // for remove item with index == 5
console.log(result1);
console.log(result2);
你可以轻而易举地用过滤过滤器方法 :
function remove(arrOriginal, elementToRemove){
return arrOriginal.filter(function(el){return el !== elementToRemove});
}
console.log(remove([1, 2, 1, 0, 3, 1, 4], 1));
这将清除数组中的所有元素, 并且运行速度比slice
和indexOf
.
您可以在 JavaScript 以多种方式完成此任务
如果您知道该值的索引:在此情况下,您可以使用复数
var arr = [1,2,3,4]
// Let's say we have the index, coming from some API
let index = 2;
// splice is a destructive method and modifies the original array
arr.splice(2, 1)
如果您没有索引, 并且只有数值: 在此情况下, 您可以使用过滤器
// Let's remove '2', for example
arr = arr.filter((value)=>{
return value !== 2;
})