Home > front end >  Loop backwards Javascript Array
Loop backwards Javascript Array

Time:10-25

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.

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(valid1));

CodePudding user response:

why -1s?

It is because of arr.indexOf(i) when the loop starts i=15 so:

arr.indexOf(15) will return -1 because you don't have a 15 in your array.

next i=14 same as above.

. . .

i=9 then it will find the element at index 3.

CodePudding user response:

As UnholySheep explains above, Array.indexOf(i) gives you the index of the first occurrence of the value represented by i in the array. 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
  }
}
  • Related