xylar
xylar

Reputation: 7673

String values to Numeric Array

What is the best way to convert the string values to an int array, e.g.:

var s = '1,1,2';

to:

var a = [1,1,2];

Thanks

Upvotes: 1

Views: 2138

Answers (3)

Andy E
Andy E

Reputation: 344567

JavaScript is a dynamic-typed language, which means that it might not be so important for those array items to be numbers. If that's the case, you might want to consider just using split():

var s = '1,1,2',
    a = s.split(",");

If it is important that they're numbers, then your best bet is to iterate over them afterwards:

for (var i = 0, max = a.length; i < max; i++)
    a[i] = +a[i]; 

There's also the ECMAScript 5th Edition method map, but it's not implemented in all browsers yet.

Upvotes: 3

user113716
user113716

Reputation: 322492

If the data is secure, you could use .eval().

var a = eval( '[' + s + ']');

If you're not sure about security, you could use JSON.parse.

var a = JSON.parse( "[" + s + "]" );

...though you'll need to include a parser in browsers that don't support it natively.

Upvotes: 1

Ionuț G. Stan
Ionuț G. Stan

Reputation: 179119

"1,2,3".split(",").map(Number);

And for those browsers that don't implement map, take an implementation like this one from here: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/map

Array.prototype.map is in ECMAScript5, so don't be afraid to augment Array.prototype.

Upvotes: 5

Related Questions