iterate through a map in javascript

后端 未结 5 1647
温柔的废话
温柔的废话 2021-02-01 13:13

I have a structure like this:

var myMap = {
    partnr1: [\'modelA\', \'modelB\', \'modelC\'],
    partnr2: [\'modelA\', \'modelB\', \'modelC\']
};
5条回答
  •  野性不改
    2021-02-01 13:53

    The callback to $.each() is passed the property name and the value, in that order. You're therefore trying to iterate over the property names in the inner call to $.each(). I think you want:

    $.each(myMap, function (i, val) {
      $.each(val, function(innerKey, innerValue) {
        // ...
      });
    });
    

    In the inner loop, given an object like your map, the values are arrays. That's OK, but note that the "innerKey" values will all be numbers.

    edit — Now once that's straightened out, here's the next problem:

        setTimeout(function () {
    
          // ...
    
        }, i * 6000);
    

    The first time through that loop, "i" will be the string "partnr1". Thus, that multiplication attempt will result in a NaN. You can keep an external counter to keep track of the property count of the outer map:

    var pcount = 1;
    $.each(myMap, function(i, val) {
      $.each(val, function(innerKey, innerValue) {
        setTimeout(function() {
          // ...
        }, pcount++ * 6000);
      });
    });
    

提交回复
热议问题