如何从数组中删除一个特定值? 类似 :
array.remove(value);
我必须使用核心核心核心JavaScript。 不允许框架 。
如何从数组中删除一个特定值? 类似 :
array.remove(value);
我必须使用核心核心核心JavaScript。 不允许框架 。
当前回答
根据索引删除
函数返回在索引中没有元素的数组副本 :
/**
* removeByIndex
* @param {Array} array
* @param {Number} index
*/
function removeByIndex(array, index){
return array.filter(function(elem, _index){
return index != _index;
});
}
l = [1,3,4,5,6,7];
console.log(removeByIndex(l, 1));
$> [ 1, 4, 5, 6, 7 ]
以值删除
函数返回没有值的数组副本。
/**
* removeByValue
* @param {Array} array
* @param {Number} value
*/
function removeByValue(array, value){
return array.filter(function(elem, _index){
return value != elem;
});
}
l = [1,3,4,5,6,7];
console.log(removeByValue(l, 5));
$> [ 1, 3, 4, 6, 7]
其他回答
let someArr = [...Array(99999).keys()]
console.time('filter')
someArr.filter(x => x !== 6666)
console.timeEnd('filter')
console.time('splice by indexOf')
someArr.splice(someArr.indexOf(6666), 1)
console.timeEnd('splice by indexOf')
在我的机器上splice
更快。这有道理,因为splice
仅编辑现有的数组,而filter
创建新数组。
尽管如此,filter
逻辑上更清洁(容易阅读),更适合使用不可改变状态的编码风格。所以由你决定是否进行这种权衡决定。
这里有很多奇妙的答案, 但对我来说,最有效的答案 不是完全从阵列中移除我的元素, 而是简单地设定它的价值为无效。
这对大多数情况都有效,而且是一个很好的解决方案,因为我稍后会使用变量,而不想让变量消失,只是暂时空的。此外,这个方法完全可以交叉浏览。
array.key = null;
定义:
function RemoveEmptyItems(arr) {
var result = [];
for (var i = 0; i < arr.length; i++) if (arr[i] != null && arr[i].length > 0) result.push(arr[i]);
return result;
}
用法 :
var arr = [1,2,3, "", null, 444];
arr = RemoveEmptyItems(arr);
console.log(arr);
正在删除带有索引和相交点的值 !
function removeArrValue(arr,value) {
var index = arr.indexOf(value);
if (index > -1) {
arr.splice(index, 1);
}
return arr;
}
查找index
使用indexOf
,然后删除该索引splice
.
组合法通过删除现有元素和/或添加新元素来改变数组的内容。
const array = [2, 5, 9];
console.log(array);
const index = array.indexOf(5);
if (index > -1) { // only splice array when item is found
array.splice(index, 1); // 2nd parameter means remove one item only
}
// array = [2, 9]
console.log(array);
第二个参数的第二个参数splice
是要删除的元素数。请注意splice
修改现有数组,并返回含有已删除元素的新数组。
由于完整性的原因,此处为函数。第一个函数只删除一个单一事件(即删除第一个匹配5
调自[2,5,9,1,5,8,5]
),而第二个函数删除所有事件:
function removeItemOnce(arr, value) {
var index = arr.indexOf(value);
if (index > -1) {
arr.splice(index, 1);
}
return arr;
}
function removeItemAll(arr, value) {
var i = 0;
while (i < arr.length) {
if (arr[i] === value) {
arr.splice(i, 1);
} else {
++i;
}
}
return arr;
}
// Usage
console.log(removeItemOnce([2,5,9,1,5,8,5], 5))
console.log(removeItemAll([2,5,9,1,5,8,5], 5))
在类型Script中,这些函数可用类型参数保持类型安全:
function removeItem<T>(arr: Array<T>, value: T): Array<T> {
const index = arr.indexOf(value);
if (index > -1) {
arr.splice(index, 1);
}
return arr;
}