let newArray = ['t', 'r', 'c', 'g', 't', 'h'];
for (let i = 0; i < newArray.length; i++) {
const x = newArray.indexOf([i])
console.log(x)
}
我是 javascript 的初学者,我不明白为什么这段代码不起作用。 我试图以最简单的方式产生这个结果:
0:4
1:-1
2:-1
3:-1
4:-1
5:-1
相反,它迭代数组并生成 6 x -1。即使数组中的第一个元素确实再次出现。 感谢您帮助理解为什么会发生这种情况以及如何解决它
最佳答案
据我了解,您想要找到数组序列中重复项的第一个后续位置。
原始答案
这可以通过 findIndex
来完成,它需要一个回调来确定索引是否算作找到。在这里您可以指定项目需要等于并且索引需要大于当前索引,因此它是一个重复项目。
let newArray = ['t', 'r', 'c', 'g', 't', 'h'];
for (let i = 0; i < newArray.length; i++) {
// Find the index of the first item which index is greater than the current item and the latter equals the item
const x = newArray
.findIndex((item, index) => index > i && newArray[i] === item);
console.log(`${i}: ${x}`);
}
更好的解决方案
正如评论中提到的(感谢 T.J. Crowder),indexOf
采用第二个参数作为开始搜索的偏移量。这是更好的解决方案,因为它更快、更简洁。
let newArray = ['t', 'r', 'c', 'g', 't', 'h'];
for (let i = 0; i < newArray.length; i++) {
const x = newArray.indexOf(newArray[i], i+1);
console.log(`${i}: ${x}`);
}
关于Javascript 在 for 循环中使用 indexOf(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59396013/