说我有以下数组:
const array = ['1', '2', '3', '1', '2', '3']
我想使用以下内容找到索引“ 2”
let index = array.findIndex(c => c === '2');
在这种情况下,索引将为1,但我想从索引2开始,因此结果将为4而不是1。
有什么想法吗?谢谢
const array = ['1', '2', '3', '1', '2', '3'];
let index = array.findIndex(c => c === '2');
console.log(index);
答案 0 :(得分:3)
您可以使用Array.indexOf()
并将fromIndex
(第二个参数)设置为2:
const array = ['1', '2', '3', '1', '2', '3'];
const index = array.indexOf('2', 2);
console.log(index);
如果必须使用Array.findIndex()
(例如,查找对象),则可以使用传递给回调(索引)的第二个参数来限制搜索:
const array = ['1', '2', '3', '1', '2', '3'];
const index = array.findIndex((c, idx) => idx > 1 && c === '2');
console.log(index);