如何从数组中删除一个特定值? 类似 :
array.remove(value);
我必须使用核心核心核心JavaScript。 不允许框架 。
如何从数组中删除一个特定值? 类似 :
array.remove(value);
我必须使用核心核心核心JavaScript。 不允许框架 。
当前回答
从数组中删除项目的最佳方法是使用过滤法。.filter()
返回没有过滤过的项目的新数组。
items = items.filter(e => e.id !== item.id);
这个.filter()
将当前项目推到过滤的阵列中。更多信息过滤过滤器 在这里.
其他回答
例如,您有一个字符数组,想要从数组中删除“A”。
数组有一个过滤方法,可以过滤并只返回您想要的元素。
let CharacterArray = ['N', 'B', 'A'];
我想返回元素 除了"A"。
CharacterArray = CharacterArray.filter(character => character !== 'A');
字符阵列必须是 : ['N', 'B']
通常比较好的是 创造一个新的阵列filter
函数。
let array = [1,2,3,4];
array = array.filter(i => i !== 4); // [1,2,3]
这还提高了易读性IMHO。slice
虽然它知道有时你应该去。
最简单的方法可能是使用过滤功能。例如:
let array = ["hello", "world"]
let newarray = array.filter(item => item !== "hello");
console.log(newarray);
// ["world"]
spolice () 函数能够将数组中的项目还给您, 从特定的索引中删除项目 / 项 :
function removeArrayItem(index, array) {
array.splice(index, 1);
return array;
}
let array = [1,2,3,4];
let index = 2;
array = removeArrayItem(index, array);
console.log(array);
从字符串阵列中查找和删除一个特定的字符串:
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