How javascript foreach works with multi-dimensional arrays?

后端 未结 3 1124
生来不讨喜
生来不讨喜 2021-02-09 17:58

I was playing a bit with javascript and found out (at least for me) strange behaviour when dealing with multi-dimensional arrays via a foreach loop. So I have this piece of code

相关标签:
3条回答
  • 2021-02-09 18:16

    There were some good point from Erick Mickelsen pointed out but so sum it up.

    1. for (... in ...) loop iterates over object properties
    2. array IS an object in Javascript so you may iterate over an array with it. But it will be slower and it is generaly not recommended (see why is that)
    3. The fact that it iterates over properties rather than values means, that it returns indexes rather than array values (this may be handy when you have associative arrays)
    4. The example in the question may be solved with for (... in ...) loop

    as follows:

    var third = '';
    for (var arrayIndex in arr) {
      third += ' ' + arr[arrayIndex][0] + ' ' + arr[arrayIndex][1];
    }
    

    In the associative array example the for (... in ...) loop will be handy:

    var person = [];
    person["id"] = 1;
    person["born"] = 2009;
    person["favourite_meal"] = "chicken"; 
    
    var fourth = '';
    for (var arrayIndex in person) {
      fourth += ' ' + person[arrayIndex];
    }
    
    0 讨论(0)
  • 2021-02-09 18:19

    for (... in ...) iterates over the properties of an object, not the elements of an array. w3schools, javascript garden

    0 讨论(0)
  • 2021-02-09 18:33

    I use this dump() function all the time to debug my multi-dimensional arrays.

    http://binnyva.blogspot.com/2005/10/dump-function-javascript-equivalent-of.html

    If you have questions about implementing it, let me know.

    0 讨论(0)
提交回复
热议问题