0

Let's suppose we have, for instance:

const array = [1, 0, 1, 1, 0]

In case I do this:

for(const el of array) console.log(array.indexOf(el))

I will always get either 0 or 1 because it will search for the first occurrence that matches the value. How do I refer to the element within an array precisely by its index? That is, how to get "0, 1, 2, 3, 4" in that case? Or even with a more than one dimension array, for example.

  • 1
    You can just run a regular for loop over it and have access to the index which then you can use to reference the array element `array[index]` – fynmnx Jul 21 '22 at 20:23

1 Answers1

0

Loop through the array and print the index

for(let i = 0; i < array.length; i++){
  array[i] === 1 && console.log(i); 
}
Sean
  • 1,368
  • 2
  • 9
  • 21