代码是当数组中的值与索引相同时,返回数组中最低的索引。如果没有匹配项,我应该返回 -1。例如:
indexEqualsValue([-8,0,2,5])
output: 2 //array[2] == 2
indexEqualsValue([-1,0,3,6])
output: -1 //no matches
代码在没有匹配项或数组长度为零时有效,但在其他时间无效。我认为问题是我的 if 语句中的第一个条件。我不一定想要答案,更多关于我应该检查/重写的提示。
谢谢!
function indexEqualsValue(a) {
return a.reduce((acc, currV, currI) => {
if (currI === currV) {
return currV;
}
return -1;
}, 0);
}
最佳答案
你可以用 Array#findIndex
找到索引.
const indexEqualsValue = array => array.findIndex((v, i) => v === i);
console.log(indexEqualsValue([-8, 0, 2, 5])); // 2
console.log(indexEqualsValue([-1, 0, 3, 6])); // -1
关于javascript - 测试数组索引是否等于数组值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51895039/