Why does this happen when the for in loop is used in Javascript?

This question already has an answer here:

  • Why is using “for…in” with array iteration a bad idea? 25 answers

  • for-in loops do not loop through the values of elements, it loops through the keys.

    An array does have keys, using indexes, so what you get for each elem is the index.

    A resource for you: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in


    for ... in loops loop over the keys of the object specified in after in . The keys of your array are 0, 1, 2 (arrays are objects with key value pairs).


    This is because you are using an array. Arrays are just objects whose keys are indices.

    ie

    [9, 8, 7] => {0: 9, 1: 8, 2: 7}
    

    Once you understand this implementation, you'll see that it is actually doing the right thing.

    链接地址: http://www.djcxy.com/p/70034.html

    上一篇: 检查数组的每个元素

    下一篇: 为什么在JavaScript中使用for循环时会发生这种情况?