samedi 4 août 2018

Why do I need .length to find the equivalence of array elements in a for loop?

The problem I'm working on iterates over an array but has three distinct behaviors depending on where in the array I am: 1. The last element: do A; 2. The second to last element: do B; 3. All other elements: do C.

To identify my position, I was using if statements, and noticed that my if statements do not evaluate as expected when I simply use an index of [-1] and [-2]. Why?

for(let i = 0; i < arr.length; i++){
  if (arr[i] === arr[arr.length-1]){console.log(`last itme`)} // This one evaluates i to be equal to the last item in the array when i is length-1
  if (arr[i] === arr[-1]){console.log(`last itme`)} // This one *does not* evaluates i to be equal to the last item in the array when i is length-1
}

Apologies if this is a duplicate - I did search and couldn't find anything that looked similar. Thanks!

Aucun commentaire:

Enregistrer un commentaire