如何从数组中删除一个特定值? 类似 :
array.remove(value);
我必须使用核心核心核心JavaScript。 不允许框架 。
如何从数组中删除一个特定值? 类似 :
array.remove(value);
我必须使用核心核心核心JavaScript。 不允许框架 。
当前回答
内咖啡冲咖啡:
my_array.splice(idx, 1) for ele, idx in my_array when ele is this_value
其他回答
非就地解决办法
arr.slice(0,i).concat(arr.slice(i+1));
let arr = [10, 20, 30, 40, 50]
let i = 2 ; // position to remove (starting from 0)
let r = arr.slice(0,i).concat(arr.slice(i+1));
console.log(r);
您可以在 JavaScript 以多种方式完成此任务
如果您知道该值的索引:在此情况下,您可以使用复数
var arr = [1,2,3,4]
// Let's say we have the index, coming from some API
let index = 2;
// splice is a destructive method and modifies the original array
arr.splice(2, 1)
如果您没有索引, 并且只有数值: 在此情况下, 您可以使用过滤器
// Let's remove '2', for example
arr = arr.filter((value)=>{
return value !== 2;
})
const arr = [1, 2, 3, 4, 5]
console.log(arr) // [ 1, 2, 3, 4, 5 ]
假设你想从Arr删除3号
const newArr = arr.filter(w => w !==3)
console.log(newArr) // [ 1, 2, 4, 5 ]
从字符串阵列中查找和删除一个特定的字符串:
var colors = ["red","blue","car","green"];
var carIndex = colors.indexOf("car"); // Get "car" index
// Remove car from the colors array
colors.splice(carIndex, 1); // colors = ["red", "blue", "green"]
资料来源:https://www.codegrepper.com/?search_term=remove+a+particular+element+from+array
const Delete = (id) => {
console.log(id)
var index = Array.map(function(e){
return e.id;
}).indexOf(id);
Array.splice(index,1);
}