Reputation: 1654
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"]
Upvotes: 0
Views: 161
Reputation: 178094
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
}
Upvotes: 2
Reputation: 1355
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
Upvotes: 0
Reputation: 138
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
}
Upvotes: 2
Reputation: 557
use this
array=JSON.parse(array);
for (var i = 0; i < array.length; i++) {
alert(array[i]);
//Do something
}
Upvotes: 1