开发者

From well formatted string to an array

In JavaScript, what is the best way to convert a well formatted string ("4,5,7,2") to an array ([4,5,7,2]):

var _intStr="3,5,7,8"var _intArr=[3,5开发者_高级运维,7,8]


var _intArr = _intStr.split(",");

One thing worth mentioning is that such value _intStr = "5,,1" will produce array with three items, two are the expected "5" and "1" and one item which is empty string.


Use the split function to split by a string or regex.

var arr = "1,2".split(",");

Now, if you actually want the elements of the resulting array to be numbers instead of strings, you can do something like this:

var arr = [];
"1,2,3,4,5".replace(/(?:'[^]*')|(?:[^, ]+)/g, function(match) {
    if (match) {
        arr[arr.length] = parseInt(match, 10);
    }
});


Ok, thanks all for your helps.

I summarized your help in this way:

String.prototype.toArrInt = function(){

   _intStr =       this.replace(/^,+|,+(,)|,+$/g, '$1').split(',')
   for(var i=0,_intArr=[];i<_intStr.length;_intArr.push(parseInt(_intStr[i++])));
   return _intArr;

}

"3,5,6,,5".toArrInt();

Please correct me or improve my final code if is needed. Thanks,

Antonio

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜