从数组中删除一定范围的元素

Remove a range of elements from an array

我想从 array:

中删除一系列元素

var fruits = ["Banana", "Orange1", "Apple", "Banana", "Orange", "Banana", "Orange", "Mango", "Bananax", "Orangex"];
var a = fruits.indexOf("Apple");
var b = fruits.indexOf("Mango");

var removedCars = fruits.splice(a, b);

console.log(fruits);

所以我期待:

["Banana", "Orange1", "Bananax", "Orangex"]

但结果是:

["Banana", "Orange1", "Orangex"]

为什么会这样?

有没有更快更好的方法?

Array.prototype.splice()方法的第二个参数是要删除的元素数,而不是结束索引。

Array.prototype.splice() MDN Reference可以看出:

Parameters

start Index at which to start changing the array (with origin 0). If greater than the length of the array, actual starting index will be set to the length of the array. If negative, will begin that many elements from the end of the array (with origin 1) and will be set to 0 if absolute value is greater than the length of the array.

deleteCount Optional An integer indicating the number of old array elements to remove. If deleteCount is 0, no elements are removed. In this case, you should specify at least one new element. If deleteCount is greater than the number of elements left in the array starting at start, then all of the elements through the end of the array will be deleted.

解法:

您需要计算这两个索引之间的元素数量,因此请使用 b-a+1 以获得正确的计数。

演示:

你的代码应该是这样的:

var fruits = ["Banana", "Orange1", "Apple", "Banana", "Orange", "Banana", "Orange", "Mango", "Bananax", "Orangex"];
var a = fruits.indexOf("Apple");
var b = fruits.indexOf("Mango");

var removedFruits = fruits.splice(a, b-a+1);

console.log(fruits);

这是使用过滤器的一种方法:

var fruits = ["Banana", "Orange1", "Apple", "Banana", "Orange", "Banana", "Orange", "Mango", "Bananax", "Orangex"];
var a = fruits.indexOf("Apple");
var b = fruits.indexOf("Mango");

//returns items not equal to a or b
function fruitfilter(item, index){
return index !== a && index !== b;
}

//apply the filter to the array, returns a new array
var newfruits = fruits.filter(fruitfilter);
 //log the new fruits
console.log(newfruits);

这是一个 jsfiddle:link

发生这种情况是因为 array.splice() 采用第一个索引和要删除的元素数而不是最后一个索引 试试看

fruits.splice(a, b - a + 1);