0

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

4 Answers 4

8

Create the array by calling split() on the string:

var visList = '1234,5678,9'  
var visListArray = visList.split(",");

You cannot substitue a string that looks like code for actual code. While this would work:

var visListArray = new Array(1234,5678,9);

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 the map() method:

visListArray = visList.split(",").map(function (item) {
    return +item;
});

See the compatibility note for using map() in older browsers.

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

Comments

1

because its an string, try this:

var visList = '1234,5678,9'
var visListArray = [].concat(visList.split(','));
for (i = 0; i <= visListArray.length - 1; i++) {
    alert(visListArray[i]);
}

2 Comments

to initialize the array with starting values,
@Shlomi - the call to concat is totally redundant.
1

You have to use string.split

var visList = '1234,5678,9'
var visListArray = visList.split(",");

for (i = 0; i <= visListArray.length - 1; i++)
{
    alert(visListArray[i]);
}

1 Comment

The OP doesn't have to use split, something like var s = '1234,5678,9'.match(/\d+/g); will do the trick also.
1

To convert a symbol-separated list into an array, you may use split(symbol):

var list = "1221,2323,4554,7667".split(",");
for (var i = 0, il = list.length; i < il; i++) {
    alert( +list[i] ); // a casting from string to number
}

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.