Convert javascript array to string

Neo picture Neo · Mar 13, 2011 · Viewed 431.5k times · Source

I'm trying to iterate over a "value" list and convert it into a string. Here is the code:

var blkstr = $.each(value, function(idx2,val2) {                    
     var str = idx2 + ":" + val2;
     alert(str);
     return str;
}).get().join(", ");    

alert() function works just fine and displays the proper value. But somehow, jquery's .get() function doesn't get the right sort of object and fails. What am I doing wrong?

Answer

If value is associative array, such code will work fine:

var value = { "aaa": "111", "bbb": "222", "ccc": "333" };
var blkstr = [];
$.each(value, function(idx2,val2) {                    
  var str = idx2 + ":" + val2;
  blkstr.push(str);
});
console.log(blkstr.join(", "));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>

(output will appear in the dev console)

As Felix mentioned, each() is just iterating the array, nothing more.