One operation that seems to be more difficult than it should be in every programming language is removing a value from an array. It's such an easy concept mentally that it skews our programmatic view of the task. In JavaScript the splice method is of huge help in removing an item from an array.
一种似乎比每种编程语言都要困难的操作是从数组中删除一个值。 从心理上讲,这是一个简单的概念,它歪曲了我们对该任务的编程观点。 在JavaScript中,拼接方法在从数组中删除项目方面有很大帮助。
JavaScript拼接 (JavaScript Splice)
One splice
coupled with an indexOf
removes the item from an array:
一个结合有indexOf
splice
将从数组中删除该项目:
// Start with an initial array
var array = ["a", "b", "c"];
// Find and remove item from an array
var i = array.indexOf("b");
if(i != -1) {
array.splice(i, 1);
}
Of course if you'd like to remove multiple occurrences of the same string/number, you'll need add a bit more logic:
当然,如果您想删除同一字符串/数字的多次出现,则需要添加一些逻辑:
for(var i = array.length-1; i--;){
if (array[i] === "b") array.splice(i, 1);
}
You may be thinking that the filter
method would work...
您可能会认为filter
方法会起作用...
array.filter(function(i) {
return i != "b"
});
...but that will return a new array, thus not modifying the original.
...但是这将返回一个新数组,因此不会修改原始数组。
Removing a given value from an array isn't too difficult of a task when you have a reliable snippet nearby!
当附近有可靠的代码段时,从数组中删除给定值并不是一件容易的事!