0

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));
3
  • 1
    Why are you calling arr.indexOf(i) if you really want to log i? Commented Oct 24, 2021 at 14:06
  • i am trying to log the index of each element to see the index because i am trying to use their indexes Commented Oct 24, 2021 at 14:12
  • 1
    But the index is i, not arr.indexOf(i). arr.indexOf(i) looks for an element with value i in the array and returns its index. That is absolutely not what you want to do Commented Oct 24, 2021 at 14:15

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.