如何删除第一个元素之后的下一个元素?

How to remove the next element after the first?

我的目标是获取数组中与我的条件相匹配的所有其他元素,但我无法做到这一点。

因此,我开始尝试在 MDNArray.prototype.indexOf() 中找到的另一个示例。

var beasts = ['ant', 'bison', 'camel', 'duck', 'bison', 'duck', 'duck', 'bison', "duck", 'bison',"camel", "duck", "duck"];

beasts.splice(beasts.indexOf("bison",beasts.indexOf("bison"+1)),1);
console.log(beasts);

我希望它从数组中删除第二个 "bison" 但它删除了最后一个元素 "duck"...

我可以在这里做什么? (当然我可能还没有学会这些东西的正确语法)

这是工作方式

let beasts = ['ant', 'bison', 'camel', 'duck', 'bison', 'duck', 'duck', 'bison', "duck", 'bison',"camel", "duck", "duck"];

beasts.splice(beasts.indexOf("bison",beasts.indexOf("bison")),1);
console.log(beasts);

您需要修正您的 indexOf 语法

beasts.indexOf("bison"+1)  // this searches for `bison1`

至此

beasts.indexOf("bison") + 1

var beasts = ['ant', 'bison', 'camel', 'duck', 'bison', 'duck', 'duck', 'bison', "duck", 'bison',"camel", "duck", "duck"];

beasts.splice(beasts.indexOf("bison",beasts.indexOf("bison")+1),1)
console.log(beasts);

你的拼接代码只有一个错误,已经在评论中找到了(It should be: beasts.indexOf("bison") + 1 and not beasts.indexOf("bison"+1)如@adiga所述)

不过,我的猜测是您实际上想从列表中删除 所有'bison' 实例。我可能在那里错了,但这是一个猜测。您可以使用过滤器来做到这一点:

var beasts = ['ant', 'bison', 'camel', 'duck', 'bison', 'duck', 'duck', 'bison', "duck", 'bison',"camel", "duck", "duck"];

const updatedBeasts = beasts.filter(beast => beast !== 'bison');

console.dir(updatedBeasts);

问题是您要 bison+1 而不是 bison 所以试试这个:

var beasts = ['ant', 'bison', 'camel', 'duck', 'bison', 'duck', 'duck', 'bison', "duck", 'bison',"camel", "duck", "duck"];

beasts.splice(beasts.indexOf("bison",beasts.indexOf("bison")),1);
console.log(beasts);

您的代码中有一些小错误导致了您的输出。
首先,要从数组中删除一个元素,我们可以使用 splice() 方法,如下所示。

array.splice(starting_index_from_which_the elements_are_to_be_deleted, number_of_elements_to_be_deleted)

如果大于数组的长度,开始将设置为数组的长度。
您的代码的正确格式是:

var beasts = ['ant', 'bison', 'camel', 'duck', 'bison', 'duck', 'duck', 'bison', "duck", 'bison',"camel", "duck", "duck"];

beasts.splice(beasts.indexOf("bison"),beasts.indexOf("bison")+1);
console.log(beasts);