简体   繁体   English

向后循环 Javascript 数组

[英]Loop backwards Javascript Array

I would like to loop backwards in a array in javascript and then get the index of each element in the array for example if a array has 10 elements and is looped backwards it would log 9, 8, 7, 6, 5, 4, 3, 2, 1, 0. for some werid reason i am getting a bunch of negaitive -1s and im confused why it wont just return the index properly.我想在 javascript 中的数组中向后循环,然后获取数组中每个元素的索引,例如,如果数组有 10 个元素并且向后循环,它将记录 9、8、7、6、5、4、3 , 2, 1, 0. 出于某种奇怪的原因,我得到了一堆否定的 -1,我很困惑为什么它不会正确返回索引。

here is the code这是代码

//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--) {
console.log(arr.indexOf(i));
}


}

console.log(validateCred(valid5));

why -1 s?为什么是-1秒?

It is because of arr.indexOf(i) when the loop starts i=15 so:这是因为arr.indexOf(i)当循环开始时i=15所以:

arr.indexOf(15) will return -1 because you don't have a 15 in your array. arr.indexOf(15)将返回-1因为您的数组中没有15

next i=14 same as above.接下来i=14同上。

. . . . . .

i=9 then it will find the element at index 3 . i=9然后它将在索引3处找到元素。

As UnholySheep explains above, Array.indexOf(i) gives you the index of the first occurrence of the value represented by i in the array.正如 UnholySheep 上面解释的那样,Array.indexOf(i) 为您提供数组中 i 表示的值第一次出现的索引。 Here is some code to help you debug:下面是一些帮助您调试的代码:

function validateCred(arr) {
  let sum = 0
  for (let i = arr.length - 1; i >= 0; i--) {
    console.log(i)        // log the index
    console.log(arr[i])   // log the value
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM