如何从数组中删除一个特定值? 类似 :
array.remove(value);
制约:我必须使用核心 JavaScript 。 框架不允许 。
如何从数组中删除一个特定值? 类似 :
array.remove(value);
制约:我必须使用核心 JavaScript 。 框架不允许 。
当前回答
一种用ES6扩展操作器从数组中去除元素的永恒方式。
比方说你想删除4。
let array = [1,2,3,4,5]
const index = array.indexOf(4)
let new_array = [...array.slice(0,index), ...array.slice(index+1, array.length)]
console.log(new_array)
=> [1, 2, 3, 5]
其他回答
const Delete = (id) => {
console.log(id)
var index = Array.map(function(e){
return e.id;
}).indexOf(id);
Array.splice(index,1);
}
您可以为此创建一个原型。只需通过数组元素和您想要从数组元素中删除的值:
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) );
此函数从特定位置的数组中删除元素。
数组. remove( 位置) ;
Array. prototype. remove = 函数 (pos) {此. splice(pos, 1);} var arr = ["a", "b", "c", "d", "e"]; arr. remove(2); // 移除"c" 控制台.log(ar);
如果您不知道要删除的项目的位置, 请使用这个 :
array.erase(element);
Array. prototype. erase = 函数( el) { let p = this. indexof (el); // indexof use prettical equality () { this. spliice (p, 1);}} var ar ar = ["a", "b", "c", "d", "e"; arr.erase (c"); 控制台. log (a) ;
最简单的方法可能是使用过滤功能。例如:
让数组 = ["哈罗","世界"] 让新数组 = 数组. filter (项目 \\\ 项 ! =@ hello ) ; 控制台. log (新数组) ; // ["世界" ]
非就地解决办法
arr.slice(0,i).concat(arr.slice(i+1));
arr = [10, 20, 30, 40, 50] (i) = 2;// 位置删除(从0开始) ; r = ar. selice (0, i). concat (arr. slice (i+1)); 控制台.log(r);