This question already has answers here:
Why is using “for…in” with array iteration a bad idea?
                            
                                (27个答案)
                            
                    
                3年前关闭。
        

    

在以下代码中,为什么将我视为字符串?我必须将其乘以1才能将其转换回数字。

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

最佳答案

只需使用普通的for循环,就不会出现此问题:

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

07-24 17:48