gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 07:12:57 25 4
gpt4 key购买 nike

我想从数组中删除一系列元素:

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). Ifgreater than the length of the array, actual starting index will beset to the length of the array. If negative, will begin that manyelements from the end of the array (with origin 1) and will be set to0 if absolute value is greater than the length of the array.

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

解决方法:

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

演示:

这是正确使用splice的代码:

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);

关于javascript - 从数组中删除一定范围的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46198689/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com