You can use Array.map
to convert each element into a number.
var a = "1,2,3,4";
var b = a.split(',').map(function(item) {
return parseInt(item, 10);
});
Check the Docs
Or more elegantly as pointed out by User: thg435
var b = a.split(',').map(Number);
Where Number()
would do the rest:check here
Note: For older browsers that don't support map
, you can add an implementation yourself like:
Array.prototype.map = Array.prototype.map || function(_x) {
for(var o=[], i=0; i<this.length; i++) {
o[i] = _x(this[i]);
}
return o;
};
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…