I am trying to work with arrays in javascript. Consider the following code:
var visList = '1234,5678,9'
var visListArray = new Array(visList);
for (i = 0; i <= visListArray.length - 1; i++)
{
alert(visListArray[i]);
}
Why doesn’t this split the array into individual numbers instead of all of them clumped together?
Any help would be really appreciated.
Many thanks
Create the array by calling
split()on the string:You cannot substitue a string that looks like code for actual code. While this would work:
Yours doesn’t because the string is not interpreted by the Array constructor as 3 comma separated arguments, it is interpreted as one string.
Edit: Note that calling
split()on a string results in an Array of strings. If you want an Array of numbers, you’ll need to iterate the Array converting each string to a number. One convenient way to do that is to use themap()method:See the compatibility note for using
map()in older browsers.