0

I have this jquery code:

function(returnArray){
     for (i=0; i<returnArray.length; i++) {
         $('<li class="tagSuggestTag"/>').appendTo('#tagSuggest ul').text(returnArray[i]);
     }

return array is an array, but for some reason when I do this it loops through every letter of the array instead of each value in the array.

The returnArray is ["hello", "helloe", "helloer"] and that loop goes through and returns:

enter image description here

6
  • 5
    Are you sure returnArray is an array? It looks like it's the string '["hello", "helloe", "helloer"]'. Commented Apr 9, 2011 at 15:56
  • Seems like returnArray is a string (especially since the first output char is a [) - could you post the code that creates it? Commented Apr 9, 2011 at 15:56
  • @Dunes @Anders Lindahl actually it might be now that I think about it. It is coming for a php echo of a json_encode() of an array. Any idea if that would return a string? Commented Apr 9, 2011 at 15:58
  • If thats true any idea how I would do a loop like thing just with the string, I am assuming I should use regexp just not sure exactly what after that Commented Apr 9, 2011 at 16:01
  • 1
    If it's in json format and you're using jquery, why not use the jQuery.parseJSON function? api.jquery.com/jQuery.parseJSON Commented Apr 9, 2011 at 16:05

2 Answers 2

2

It was revealed in the comments to the question that the returnarray isn't really an array, it's a JSON string representation of a string computed by the PHP function json_encode().

The function jQuery.parseJSON can turn this back into a javascript array.

Sign up to request clarification or add additional context in comments.

Comments

1

your array is a string. use:

var myarray = eval('["hello", "helloe", "helloer"]');

2 Comments

euuw - why eval? var myarray = ["hello", "helloe", "helloer"]; will work
because returnArray IS A STRING not an array. this was just an example of how to convert a string representation of an array to an actual array. the real code would be var realArray = eval(returnArray);

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.