如何从数组中删除一个特定值? 类似 :
array.remove(value);
制约:我必须使用核心 JavaScript 。 框架不允许 。
如何从数组中删除一个特定值? 类似 :
array.remove(value);
制约:我必须使用核心 JavaScript 。 框架不允许 。
当前回答
(function removeFromArrayPolyfill() {
if (window.Array.prototype.remove) return;
Array.prototype.remove = function (value) {
if (!this.length || !value) return;
const indexOfValue = this.indexOf(value);
if (indexOfValue >= 0) {
this.splice(indexOfValue, 1);
}
};
})();
// testing polyfill
const nums = [10, 20, 30];
nums.remove(20);
console.log(nums);//[10,30]
其他回答
从带有数组元素的阵列列表中获取阵列和索引 从使用地图toint () 和 Toarray () 方法的阵列新阵列中删除 使用删除 () 方法删除具体索引元素 返回格式化的阵列
一种用ES6扩展操作器从数组中去除元素的永恒方式。
比方说你想删除4。
let array = [1,2,3,4,5]
const index = array.indexOf(4)
let new_array = [...array.slice(0,index), ...array.slice(index+1, array.length)]
console.log(new_array)
=> [1, 2, 3, 5]
要从数组中删除元素, 要从数组中除去元素, 组合、 过滤和删除
每个阵列都有自己的索引,它有助于用索引删除一个特定元素。
拼盘 () 方法
array.splice(index, 1);
第一个参数是索引,第二个参数是从该索引中删除的元素数量。
因此,单一个元素,我们用1。
删除方法
delete array[index]
过滤 () 方法
如果您想要删除一个在数组中重复的元素, 那么过滤数组 :
removeAll = array.filter(e => e != elem);
Eleem 是您要从数组中删除的元素, 数组是您的数组名称 。
您只需要按元素或索引过滤 :
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);
我喜欢这个单行道:
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);
}
(是的,我读了所有其他的答案 找不到一个结合的答案 包含和串联在同一行。 )