最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript array from string of numbers - Stack Overflow

programmeradmin6浏览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

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

Share asked Nov 10, 2011 at 21:55 neojakeyneojakey 1,6535 gold badges25 silver badges37 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 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 ma 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 patibility note for using map() in older browsers.

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]);
}

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]);
}

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
}
发布评论

评论列表(0)

  1. 暂无评论