0

I'm having some trouble with my array.

It loops through every character of the array, so including the [ and ".

My code:

for (var i = 0; i < array.length; i++) {
   alert(array[i]);
   //Do something
}

The array looks like this: ["1", "2", "1"]

10
  • 4
    It seems your array is a string Commented Aug 31, 2016 at 6:09
  • 1
    It seems your "array" is not an array, but a JSON representation of an array: a string. Commented Aug 31, 2016 at 6:09
  • 4
    var array = JSON.parse(arrayString); Commented Aug 31, 2016 at 6:11
  • 3
    @KamilLatosinski— "a json"? JSON is a notation, the OP likely has a string that is an array in JSON format, or a javascript array literal. Commented Aug 31, 2016 at 6:12
  • 1
    @mplungjan In my opinion you should create a answer to this question. I will accept it as correct, because you are the first that came with the correct answer Commented Aug 31, 2016 at 6:27

4 Answers 4

2

Converting comment to answer.

Understanding that you had a string representation of an array, you can convert it to array using JSON.parse

var arrayString='["1", "2", "1"]',
    array = JSON.parse(arrayString);
for (var i = 0; i < array.length; i++) {
   console.log(array[i]);
   //Do something
}

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

1 Comment

Thanks again @mplungjan!
2

You are looping a string and thus it shows characters of the string. You might want to convert the string into an array before looping. The best way will be to use JSON.parse function.

// Add this
array = JSON.parse(array);
for (var i = 0; i < array.length; i++) {
alert(array[i]);
//Do something
}

5 Comments

Sorry, didn't notice while writing the answer. That "Go away" was unneeded though.
So I removed it... I forgot the ;)
Nice job in the comments. But shouldn't you try to answer instead? Most of the searchers do not tend to search in the comments and look directly in the answers.
@mplungjan sorry but I think it is much clearer if the comments are summerized or illustrated on an answer otherwise this site would look like an old ages forum.
Fair enough. I did not feel it was worth answering since the comments already gave OP the reason. Anyway - I converted my comment to an answer
1

use this

array=JSON.parse(array);
for (var i = 0; i < array.length; i++) {
   alert(array[i]);
   //Do something
}

1 Comment

Of course an answer is still needed. The person posting the answer as a comment made the mistake here.
0

If the browser has the JSON object then

JSON.parse(string);

or if you have jQuery

$.parseJSON(string);

Source : https://stackoverflow.com/a/9420607/5326667

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.