JavaScript倒序遍历数组获取元素索引返回-1问题求解
问题根因
你代码里的错误出在arr.indexOf(i)的使用逻辑上:
Array.indexOf()方法的入参是数组元素的值,返回值是该值在数组中第一次出现的索引,找不到对应值就返回-1- 你循环里的
i本身就是当前遍历的倒序索引,直接打印i就能得到你要的9、8、7...0的结果,不需要调用indexOf方法
修正后的代码
//Arrays I would like to pass into the function const valid1 = [4, 5, 3, 9, 6, 7, 7, 9, 0, 8, 0, 1, 6, 8, 0, 8]; const invalid1 = [4, 5, 3, 2, 7, 7, 8, 7, 7, 1, 0, 9, 1, 7, 9, 5]; function validateCred(arr) { let sum = 0; for (let i = arr.length - 1; i >= 0; i--) { // 直接打印i就是当前倒序遍历的索引 console.log(i); // 如果需要取对应元素,直接用arr[i]即可 } } validateCred(valid1);
扩展说明
如果需要同时获取倒序遍历的索引和对应元素,也可以用更简洁的写法:
function validateCred(arr) { for (const [index, item] of arr.entries().reverse()) { console.log(`当前索引:${index},对应元素:${item}`) } }
内容的提问来源于stack exchange,提问作者omarfarah
相关产品推荐
相关产品推荐

