Javascript - Trouble using for…in to iterate through an object

感情迁移 提交于 2019-12-01 07:05:55

问题


I have a dynamically-generated object that looks like this:

colorArray = { 
    AR: "#8BBDE1", 
    AU: "#135D9E", 
    AT: "#8BBDE1",
    ... }

I'm trying to use it to color a map by using this plugin and the 'colors' attribute during the call to the plugin. Like this:

$('#iniDensityMap').vectorMap({
    backgroundColor: '#c2e2f2',
    colors: colorArray,
    ... (some other params)
});

But it doesn't color in the countries. When I hard code this in, it works fine - but it must be dynamically generated for this project, so something like this won't work for me (although it does in fact color the map):

$('#iniDensityMap').vectorMap({
    backgroundColor: '#c2e2f2',
    colors: { AR: "#8BBDE1", AU: "#135D9E", AT: "#8BBDE1" },
    ... (some other params)
});

I've traced the issue far enough into the plugin to find it has something to do with this loop:

setColors: function(key, color) {
  if (typeof key == 'string') {
    this.countries[key].setFill(color);
  } else {

    var colors = key; //This is the parameter passed through to the plugin

    for (var code in colors) {

      //THIS WILL NOT GET CALLED

      if (this.countries[code]) {
        this.countries[code].setFill(colors[code]);
      }
    }
  }
},

I've also tried iterating through the colorArray object on my own, outside of the plugin and I'm running into the same issue. Whatever sits inside the for ( var x in obj ) isn't firing. I've also noticed that colorArray.length returns undefined. Another important note is that I've instantiated var colorArray = {}; in a separate call, attempting to ensure that it is sitting at the global scope and able to be manipulated.

I'm thinking that the problem is either:

  1. The way I'm dynamically populating the object - colorArray[cCode] = cColor; (in a jQuery .each call)
  2. I'm once again confusing the differences between Arrays() and Objects() in javascript
  3. It is a scope issue perhaps?
  4. Some combination of everything above.

EDIT #1: I've moved my additional question about Objects in the Console in Firebug to a new post HERE. That question deals more specifically with Firebug than the underlying JS problem I'm asking about here.

Edit #2: Additional info Here's the code I'm using to dynamically populate the Object:

function parseDensityMapXML() {
$.ajax({
    type: "GET",
    url: "media/XML/mapCountryData.xml",
    dataType: "xml",
    success: function (xml) {
        $(xml).find("Country").each(function () {
            var cName = $(this).find("Name").text();
            var cIniCount = $(this).find("InitiativeCount").text();
            var cUrl = $(this).find("SearchURL").text();
            var cCode = $(this).find("CountryCode").text();

            //Populate the JS Object
            iniDensityData[cCode] = { "initiatives": cIniCount, "url": cUrl, "name": cName };
            //set colors according to values of initiatives count
            colorArray[cCode] = getCountryColor(cIniCount);
        });
    }
});
} //end function parseDensityMapXML();

This function is then called on a click event of a checkbox elsewhere on the page. The Objects iniDensityData and colorArray are declared in the head of the html file - hoping that keeps them in global scope:

<script type="text/javascript">
    //Initialize a bunch of variables in the global scope
    iniDensityData = {};
    colorArray = {};
</script>

And finally, here's a snippet from the XML file that is being read:

<?xml version="1.0" encoding="utf-8"?>
<icapCountryData>
  <Country>
    <Name>Albania</Name>
    <CountryCode>AL</CountryCode>
    <InitiativeCount>7</InitiativeCount>
    <SearchURL>~/advance_search.aspx?search=6</SearchURL>
  </Country>
  <Country>
    <Name>Argentina</Name>
    <CountryCode>AR</CountryCode>
    <InitiativeCount>15</InitiativeCount>
    <SearchURL>~/advance_search.aspx?search=11</SearchURL>
  </Country>
  ... and so on ...
</icapCountryData>

回答1:


Solved it! Originally, I was calling the function parseDensityMapXML() and then immediately after it calling another function loadDensityMapXML() which took the object created dynamically in the first function and iterated through it. Problem was, it wasn't called as a callback from the first function, so was firing before the Object had even been built.

To fix, I just amended the first function mentioned above to call the second function after the .each() was finished creating the objects:

function parseDensityMapXML() {
$.ajax({
    type: "GET",
    url: "media/XML/mapCountryData.xml",
    dataType: "xml",
    success: function (xml) {
        $(xml).find("Country").each(function () {
            var cName = $(this).find("Name").text();
            var cIniCount = $(this).find("InitiativeCount").text();
            var cUrl = $(this).find("SearchURL").text();
            var cCode = $(this).find("CountryCode").text();

            //Populate the JS Object
            iniDensityData[cCode] = { "initiatives": cIniCount, "url": cUrl, "name": cName };
            //set colors according to values of initiatives count
            colorArray[cCode] = getCountryColor(cIniCount);
        });

        /* and then call the jVectorMap plugin - this MUST be done as a callback
           after the above parsing.  If called separately, it will fire before the
           objects iniDensityData and colorArray are created! */
        loadDensityMapXML();
    }
});
} //end function parseDensityMapXML();


来源:https://stackoverflow.com/questions/11750145/javascript-trouble-using-for-in-to-iterate-through-an-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!