如何从数组中删除一个特定值? 类似 :
array.remove(value);
制约:我必须使用核心 JavaScript 。 框架不允许 。
如何从数组中删除一个特定值? 类似 :
array.remove(value);
制约:我必须使用核心 JavaScript 。 框架不允许 。
当前回答
这取决于你是否想保持一个空位。
如果您想要一个空位 :
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 , 如果找不到的话 。
其他回答
你的问题没有说明顺序或不同的价值是否是一项要求。
如果您不关心顺序, 并且容器中的值不会超过一次, 请使用“ Set ” 。 它会更快, 更简洁 。
var aSet = new Set();
aSet.add(1);
aSet.add(2);
aSet.add(3);
aSet.delete(2);
弹出 - 从阵列变化的结尾处删除 - 从阵列复件的开头处删除 - 从特定的阵列索引过滤器中删除 - 允许您程序化地从阵列中删除元素
您可以扩展数组对象以定义自定义的删除函数如下:
let let = [1, 2,4,4,4,5,5,45,9;] 数.delete = 函数(价值) { var indexof Target = this.indexof (value) =.indexof(value) = this.if(indexoftaget = = = = = = = = = = y= = y,4,4,4,5,4,459; 数. 数.delet = 函数(val = val indexof Talget = this. indexeof(valent) = = = = = indexget =.indexof = = =. { = indexexuf(val =) { = = indexete = = / / / imme eleteletelete (1) // / / / / 预期输出= / / / tradestrayf delett 删除 2,4,4,4,4,4,4,5,5,5,4,4,5,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,9/ /
最简单的方法可能是使用过滤功能。例如:
让数组 = ["哈罗","世界"] 让新数组 = 数组. filter (项目 \\\ 项 ! =@ hello ) ; 控制台. log (新数组) ; // ["世界" ]
您可以为此创建一个原型。只需通过数组元素和您想要从数组元素中删除的值:
Array. prototype. removeTrounds = 函数( array, val) { { 数组. (raryTrounds, index) {如果 (rayTroups = val) { 数组. splice( index, 1);} 返回数组;} var DummyAray = [1、2、 3、4、 5、 6]; 控制台.log (DummyArray. removeTround (DummyArray, 3) );