如何从数组中删除一个特定值? 类似 :
array.remove(value);
制约:我必须使用核心 JavaScript 。 框架不允许 。
如何从数组中删除一个特定值? 类似 :
array.remove(value);
制约:我必须使用核心 JavaScript 。 框架不允许 。
当前回答
从数组中删除项目的最佳方法是使用过滤法。 . filter () 返回没有过滤过的项目的新数组 。
items = items.filter(e => e.id !== item.id);
. filter () 方法映射为完整的数组, 当我返回真实状态时, 它会将当前项目推到过滤的数组。 在此过滤器中读取更多 。
其他回答
更现代的ECMAScript 2015(原称和谐或ES6)方法。
const items = [1, 2, 3, 4];
const index = 2;
然后:
items.filter((x, i) => i !== index);
弹出 :
[1, 2, 4]
您可以使用 Babel 和多填充服务,以确保浏览器之间有很好的支持。
我找到了这个博客文章,
9 从 JavaScript 阵列中删除元素的方法 - 附加如何安全清除 JavaScript 阵列
我更喜欢使用过滤器 () :
var filtered_arr = arr.filter(function(ele){
return ele != value;
})
我不知道你如何期待阵列.remove( int) 的行为。 我可以想到三种可能性, 你可能会想要。
要删除索引 i 中的数组元素:
array.splice(i, 1);
如果您想要从数组中删除带有数值数的每个元素 :
for (var i = array.length - 1; i >= 0; i--) {
if (array[i] === number) {
array.splice(i, 1);
}
}
如果您只想在索引 I 中使元素不再存在, 但是您不想让其它元素的索引改变 :
delete array[i];
Array.prototype.removeItem = function(a) {
for (i = 0; i < this.length; i++) {
if (this[i] == a) {
for (i2 = i; i2 < this.length - 1; i2++) {
this[i2] = this[i2 + 1];
}
this.length = this.length - 1
return;
}
}
}
var recentMovies = ['Iron Man', 'Batman', 'Superman', 'Spiderman'];
recentMovies.removeItem('Superman');
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);
我不知道为什么 但我确认约翰的原创执行没有问题