如何从数组中删除一个特定值? 类似 :
array.remove(value);
制约:我必须使用核心 JavaScript 。 框架不允许 。
如何从数组中删除一个特定值? 类似 :
array.remove(value);
制约:我必须使用核心 JavaScript 。 框架不允许 。
当前回答
const Delete = (id) => {
console.log(id)
var index = Array.map(function(e){
return e.id;
}).indexOf(id);
Array.splice(index,1);
}
其他回答
John Resig张贴了很好的执行:
// Array Remove - By John Resig (MIT Licensed)
Array.prototype.remove = function(from, to) {
var rest = this.slice((to || from) + 1 || this.length);
this.length = from < 0 ? this.length + from : from;
return this.push.apply(this, rest);
};
如果您不想扩展一个全球对象, 可以做一些类似的东西,
// Array Remove - By John Resig (MIT Licensed)
Array.remove = function(array, from, to) {
var rest = array.slice((to || from) + 1 || array.length);
array.length = from < 0 ? array.length + from : from;
return array.push.apply(array, rest);
};
但我之所以张贴这篇文章,主要是为了提醒用户不要采取该页(2007年12月14日)评论中建议的其他实施方式:
Array.prototype.remove = function(from, to) {
this.splice(from, (to=[0, from || 1, ++to - from][arguments.length]) < 0 ? this.length + to : to);
return this.length;
};
它一开始似乎效果良好,但经过一个痛苦的过程,我发现它在试图删除数组中第二至最后一个元素时失败了。例如,如果您有一个 10 元素数组,并且试图用这个来删除第九元素:
myArray.remove(8);
我不知道为什么 但我确认约翰的原创执行没有问题
[2,3,5].filter(i => ![5].includes(i))
如果您想要 [.].remove(el) 类似语法的语法, 和其他编程语言一样, 那么您可以添加此代码 :
// Add remove method to Array prototype
Array.prototype.remove = function(value, count=this.length) {
while(count > 0 && this.includes(value)) {
this.splice(this.indexOf(value), 1);
count--;
}
return this;
}
用法
// Original array
const arr = [1,2,2,3,2,5,6,7];
// Remove all 2s from array
arr.remove(2); // [1,3,5,6,7]
// Remove one 2 from beginning of array
arr.remove(2, 1); // [1,2,3,2,5,6,7]
// Remove two 2s from beginning of array
arr.remove(2, 2); // [1,3,2,5,6,7]
您可以根据您的需求操控该方法 。
通常比较好用过滤功能创建新阵列。
let array = [1,2,3,4];
array = array.filter(i => i !== 4); // [1,2,3]
这还提高了易读性IMHO。我不是切片的粉丝, 虽然它知道有时你应该去。
尝试使用过滤器方法使用此代码, 您可以从数组中删除任何特定项 。
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
function removeItem(arr, value) {
return arr.filter(function (ele) {
return ele !== value;
});
}
console.log(removeItem(arr, 6));