Question

I'm trying to get this loop to run through 1-27 of my list, but I think it's looping through my list and only giving me an output for the last item in the list. I think I want it to update the variable every time it loops through.

I'm only getting the output for the '27' (the last item in the list) or if I remove them all, then I'll get the output for the '1'(see below).

Does anyone have any idea of how this is done?

var regionslist = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27];

var justthisregion;
var pndsplusthisregion;
var test;

var regionsplusponds = function (regionslist){

      for (var i in regionslist) {
        justthisregion = finregions.remap([regionslist[i]],[1000],0);
      }
      pndsplusthisregion = justthisregion.add(justponds);

      if (pndsplusthisregion===2000) {
          test = finregions.remap([regionslist[i]],[2000])

      } else {
          test = finregions.remap([regionslist[i]],[999])
      }
      addToMap(test, {min:0, max:2000, palette:['ff0033','993366','003366'], opacity:0.5}, "Regions with Ponds");
};
Was it helpful?

Solution

You are closing your loop too soon. This is the only line being ran 27 times justthisregion = finregions.remap([regionslist[i]],[1000],0);. So justthisregion will only end up holding whatever the last interation was. Move your } down.

var regionsplusponds = function (regionslist){
  for (var i in regionslist)
  {
    justthisregion = finregions.remap([regionslist[i]],[1000],0);
    pndsplusthisregion = justthisregion.add(justponds);
    if (pndsplusthisregion===2000)
      test = finregions.remap([regionslist[i]],[2000]);
    else
      test = finregions.remap([regionslist[i]],[999]);
    addToMap(test, {min:0, max:2000, palette:['ff0033','993366','003366'], opacity:0.5}, "Regions with Ponds");
  } /* <-- this was your problem line */
};

OTHER TIPS

Ah, your loop isn't encompassing all of the logic you're trying to iterate on. Try this:

var regionsplusponds = function (regionslist){
    for (var i in regionslist) {
        justthisregion = finregions.remap([regionslist[i]],[1000],0);
        pndsplusthisregion = justthisregion.add(justponds);
    if (pndsplusthisregion===2000){
        test = finregions.remap([regionslist[i]],[2000])}
    else{
        test = finregions.remap([regionslist[i]],[999])}
    addToMap(test, {min:0, max:2000, palette:['ff0033','993366','003366'], opacity:0.5}, "Regions with Ponds");}
};

Your for loop was reassigning justthisregion 27 times and then moving on to run the rest of the code just once. I moved the closing curly bracket of the for loop from after this line:

justthisregion = finregions.remap([regionslist[i]],[1000],0);}

to after this line:

addToMap(test, {min:0, max:2000, palette:['ff0033','993366','003366'], opacity:0.5}, "Regions with Ponds");}

That should work.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top