如何从数组中删除一个特定值? 类似 :
array.remove(value);
制约:我必须使用核心 JavaScript 。 框架不允许 。
如何从数组中删除一个特定值? 类似 :
array.remove(value);
制约:我必须使用核心 JavaScript 。 框架不允许 。
当前回答
在 ES6 中, Set 收藏提供了从数组中删除特定值的删除方法,然后根据分布运算符将 Set 收藏转换成数组。
函数 删除项目( list, val) { const set = new Set( list); set.delet( val); 设置. delete( val); 返回 [...set] ;} const 字母 = [“ A” , “ B” , “ C” , “ D” , “ E ” ; 控制台. log( deletetetetemmot( 字母, “ C ” ); / / [ “ A” , “ B” , “ D” , “ E ” 。
其他回答
您可以使用复数来从数组中删除对象或值。
让我们考虑一个长度为5的行距, 值为10,20,30,40,50, 我想从中去掉30的值。
var 数组 = [10,20,30,40,50];如果 (数组. indexof(30) > -1) {数组.spice( 数组. indexof(30), 1);} 控制台. log( 数组); / / [10,20, 40,50]
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);
我不知道为什么 但我确认约翰的原创执行没有问题
我不知道你如何期待阵列.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. removeByValue = 函数( val) {, 对于 (var i = 0; i < this. long; i++) { 如果 (i) val) { this. splice (i, 1); i- ; } 返回此 ;} var falts = [apple, 'banana', 'carrot', 'orange' ] ; falves.remove ByValue ('banana'); 礼服. log (fruts); / / - > [apple, 'carrot', 'orange' ]
咖啡:
my_array.splice(idx, 1) for ele, idx in my_array when ele is this_value