如何从数组中删除一个特定值? 类似 :
array.remove(value);
制约:我必须使用核心 JavaScript 。 框架不允许 。
如何从数组中删除一个特定值? 类似 :
array.remove(value);
制约:我必须使用核心 JavaScript 。 框架不允许 。
当前回答
对我而言,越简单越好,2018年(2019年左右),我给你这个(近一点)单行话,回答最初的问题:
Array.prototype.remove = function (value) {
return this.filter(f => f != value)
}
有用的是,你可以用在咖喱的表达方式上,比如:
[1,2,3].remove(2).sort()
其他回答
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 或_。
使用 indexof, 可以用 spolice 从数组中找到一个特定的数字索引, 从数组中删除一个特定的索引 。
const 数组 = [1,2,3,4,5,6,6,7,7,8,9,0]; const 指数 = 数组.indexof(5); /// 找到具体数字的索引 if( index != -1) { 数组.splice( index, 1); // 使用 index world. log( 数组) 删除数字 ;
删除全部事件 。 @ info: whatsthis
数组数组 = [1、2、3、4、4、5、1、7、8、9、9、2、3、4、5、6] 数组 = 数组. filter( number_@ number!=5); 控制台. log( 数组) ;
使用 join 和 share let 数组 = [1、2、3、4、5、1、7、8、9、2、3、4、5、6] 数组 = 数组 。 来自 (array.join ("-" -").split ("-5 -").join (" -").split ("-").split ("-"), number) 控制台.log (ray) 的 数组 。
这取决于你是否想保持一个空位。
如果您想要一个空位 :
array[index] = undefined;
如果你不想空空的位子:
//To keep the original:
//oldArray = [...array];
//This modifies the array.
array.splice(index, 1);
如果您需要该项的值, 您可以保存返回的数组元素 :
var value = array.splice(index, 1)[0];
如果您想要在数组的两端删除, 您可以在最后一个或数组中使用数组. pop () 。 第一个或数组中可以使用数组. translate. pop () 。 translate () toft () for first one (两者都返回项目值 ) 。
如果您不知道项目的索引, 您可以使用数组。 indexof( 项目) 来获取它( 在 if( ) 中获得一个项, 或者在 a while( ) 中获取全部项 ) 。 数组。 indexof( 项目) 返回索引, 或 - 1 , 如果找不到的话 。
我不知道你如何期待阵列.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];
我知道已经有很多答案了, 但其中许多答案似乎都使问题复杂化了。 这是一个简单的、循环的删除所有关键实例的方法- 在找不到索引之前自呼自用。 是的, 它只在有索引的浏览器中起作用, 但是它很简单, 并且很容易被多填 。
独立职能
function removeAll(array, key){
var index = array.indexOf(key);
if(index === -1) return;
array.splice(index, 1);
removeAll(array,key);
}
原型方法
Array.prototype.removeAll = function(key){
var index = this.indexOf(key);
if(index === -1) return;
this.splice(index, 1);
this.removeAll(key);
}