for … in loop with string array outputs indices

前端 未结 4 474
孤城傲影
孤城傲影 2020-12-03 11:16

When I write some javascript such as this:

var words = [\'word1\', \'word2\', \'word3\']

for (word in words) {
    console.log(word)
}

The

4条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-03 11:38

    As the other answers correctly point out, for...in is not for iterating over arrays. A better option is now available in newer JavaScript engines and transpilers like TypeScript with for...of:

    var words = ['word1', 'word2', 'word3']
    
    for (word of words) {
        console.log(word)
    }
    

提交回复
热议问题