如何从数组中删除一个特定值? 类似 :
array.remove(value);
制约:我必须使用核心 JavaScript 。 框架不允许 。
如何从数组中删除一个特定值? 类似 :
array.remove(value);
制约:我必须使用核心 JavaScript 。 框架不允许 。
当前回答
弹出 - 从阵列变化的结尾处删除 - 从阵列复件的开头处删除 - 从特定的阵列索引过滤器中删除 - 允许您程序化地从阵列中删除元素
其他回答
我找到了这个博客文章,
9 从 JavaScript 阵列中删除元素的方法 - 附加如何安全清除 JavaScript 阵列
我更喜欢使用过滤器 () :
var filtered_arr = arr.filter(function(ele){
return ele != value;
})
OK,例如,您有下面的数组:
var num = [1, 2, 3, 4, 5];
我们想要删除第4号, 你可以简单地使用下面的代码:
num.splice(num.indexOf(4), 1); // num will be [1, 2, 3, 5];
如果您正在重复使用此函数,请写入一个可重复使用的函数,该函数将附加在本地数组函数上,如下文所示:
Array.prototype.remove = Array.prototype.remove || function(x) {
const i = this.indexOf(x);
if(i===-1)
return;
this.splice(i, 1); // num.remove(5) === [1, 2, 3];
}
但如果您有下面的数组, 而不是数组中的几个 [5] 呢?
var num = [5, 6, 5, 4, 5, 1, 5];
我们需要一个循环来检查它们, 但是一个更容易和更有效的方法是使用内置的 JavaScript 函数, 所以我们写一个函数, 使用下面这样的过滤器 :
const _removeValue = (arr, x) => arr.filter(n => n!==x);
//_removeValue([1, 2, 3, 4, 5, 5, 6, 5], 5) // Return [1, 2, 3, 4, 6]
还有第三方图书馆,如Lodash 或Goint, 也帮助你这样做。更多信息,请参看 Lodash _. pull,_. pullAt 或_。
如果你想删除几个项目, 我发现这是最容易的:
const oldArray = [1, 2, 3, 4, 5]
const removeItems = [1, 3, 5]
const newArray = oldArray.filter((value) => {
return !removeItems.includes(value)
})
console.log(newArray)
产出:
[2, 4]
从数组中删除一个特定元素, 可以在过滤器选项的一行内完成, 它得到所有浏览器的支持 : https:// caniuse. com/ #search=filter% 20arary
function removeValueFromArray(array, value) {
return array.filter(e => e != value)
}
我在这里测试了此函数 : https://bit.dev/joshk/jotils/remove-value- from-array/~code#test.ts
我喜欢这个单行道:
arr.includes(val) && arr.splice(arr.indexOf(val), 1)
ES6 (无互联网探索者支持) 清除已就位 。 快速 : 没有重复重复或重复 。 支持删除无定义或未定义的值
作为原型
// 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);
}
(是的,我读了所有其他的答案 找不到一个结合的答案 包含和串联在同一行。 )