james
james

Reputation: 1041

Can't add to javascript array in loop

I'm having some issues with the following code:

var tmpArray = new Array();
for(var n in fnlArray){
    if(fnlArray[n] == largest.val){
        alert(fnlArray[n] +"-"+ largest.val);
        tmpArray[n] = fnlArray[n];
    }
}

fnlArray contents is:

fnlArray['result1'] = 1;
fnlArray['result2'] = 2;
fnlArray['result3'] = 2;
fnlArray['result4'] = 2;
and largest.val = 2;

The issue I'm having is the alert gets fired so I would expect to end up with tmpArray with the following:

tmpArray['result2'] = 2;
tmpArray['result3'] = 2;
tmpArray['result4'] = 2;

But the array (tmpArray) is always empty. Is this an issue with adding items to the array dynamically within a loop?

Upvotes: 2

Views: 2626

Answers (1)

Rob W
Rob W

Reputation: 348992

var tmpArray = new Array(); should be:

var tmpArray = {};

Your tmpArray object is not a index array, so you have to use object literals.

var tmpArray = {};
for(var n in fnlArray){
  if(fnlArray[n] == largest.val){
       tmpArray[n] = fnlArray[n];
  }
}
alert(JSON.stringify(tmpArray)); //Prints: {"result2":2,"result3":2,"result4":2}

Demo: http://jsfiddle.net/QhFGF/

Upvotes: 6

Related Questions