0

In the following code why is i treated as a string? I have to multiple it by 1 to get it to convert back to a number.

  getPositionInArray(value, array) {
    console.log('array = ', array);

    let i = 0; // why is i a string?
    for (i in array) {
      if (array[i].toLowerCase() === value) {
        let positionOnUI = i * 1 + 1; // why can't I use i + 1?
        return positionOnUI;
      }
    }
    return null;
  }
letter Q
  • 14,735
  • 33
  • 79
  • 118

2 Answers2

1

assuming the array is an array...

the problem is for(i in array) that treats the array as an object and return the indexes as strings:

change the loop in for(;i<array.length;i++) and it should work.

maioman
  • 18,154
  • 4
  • 36
  • 42
1

just use a normal for loop and you wont have this issue:

Working Example

function getPositionInArray (value, array) {
  console.log('array = ', array);
  for (let i = 0; i < array.length; i++) {
    if (array[i].toLowerCase() === value) {
      let positionOnUI = i // why can't I use i + 1?
      return positionOnUI;
    }
  }
  return null;
}
omarjmh
  • 13,632
  • 6
  • 34
  • 42