如何从数组中删除一个特定值? 类似 :
array.remove(value);
我必须使用核心核心核心JavaScript。 不允许框架 。
如何从数组中删除一个特定值? 类似 :
array.remove(value);
我必须使用核心核心核心JavaScript。 不允许框架 。
当前回答
你可以轻而易举地用过滤过滤器方法 :
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;
})
我喜欢这个单行道:
arr.includes(val) && arr.splice(arr.indexOf(val), 1)
null
或undefined
作为原型
// remove by value. return true if value found and removed, false otherwise
Array.prototype.remove = function(val)
{
return this.includes(val) && !!this.splice(this.indexOf(val), 1);
}
(是的,我读了所有其他的答案 却找不到一个结合的答案)includes
和splice
在同一行中。 )
我找到了这个博客文章,
9 从 JavaScript 阵列中删除元素的方法 - 附加如何安全清除 JavaScript 阵列
我更喜欢用filter()
:
var filtered_arr = arr.filter(function(ele){
return ele != value;
})
从数组中删除一个特定元素/字符串可在单班条中进行:
theArray.splice(theArray.indexOf("stringToRemoveFromArray"), 1);
此处:
阵列:要从
将字符串从矩阵中移除:要删除的字符串,而1是要删除的元素数量。
注 注 注 注 注注:如果“字符串要从阵列中移除”不位于数组中,这将删除数组的最后一个元素。
在移除该元素之前先检查该元素是否存在于您的阵列中, 总是很好的做法 。
if (theArray.indexOf("stringToRemoveFromArray") >= 0){
theArray.splice(theArray.indexOf("stringToRemoveFromArray"), 1);
}
取决于客户电脑上是否有新版或旧版的剪贴条:
var array=['1','2','3','4','5','6']
var newArray = array.filter((value)=>value!='3');
或
var array = ['1','2','3','4','5','6'];
var newArray = array.filter(function(item){ return item !== '3' });
“ 3” 是您想要从数组中删除的值。 然后, 数组将变成 :['1','2','4','5','6']
您可以为此创建一个原型。只需通过数组元素和您想要从数组元素中删除的值:
Array.prototype.removeItem = function(array,val) {
array.forEach((arrayItem,index) => {
if (arrayItem == val) {
array.splice(index, 1);
}
});
return array;
}
var DummyArray = [1, 2, 3, 4, 5, 6];
console.log(DummyArray.removeItem(DummyArray, 3));