简体   繁体   中英

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?

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM