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"]

Chris
  • 1,574
  • 4
  • 16
  • 49

4 Answers4

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
}
PDK
  • 138
  • 5
  • Sorry, didn't notice while writing the answer. That "Go away" was unneeded though. – PDK Aug 31 '16 at 06:14
  • So I removed it... I forgot the ;) – mplungjan Aug 31 '16 at 06:14
  • 1
    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. – PDK Aug 31 '16 at 06:18
  • @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. – C.Champagne Aug 31 '16 at 06:23
  • 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 – mplungjan Aug 31 '16 at 06:40
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
}
mplungjan
  • 169,008
  • 28
  • 173
  • 236
1

use this

array=JSON.parse(array);
for (var i = 0; i < array.length; i++) {
   alert(array[i]);
   //Do something
}
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

Community
  • 1
  • 1
Mannan Bahelim
  • 1,289
  • 1
  • 11
  • 31