admin管理员组文章数量:1414908
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
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
Share Improve this question edited Feb 10, 2011 at 17:16 Andy E 345k86 gold badges481 silver badges451 bronze badges asked Feb 10, 2011 at 16:56 xylarxylar 7,67317 gold badges59 silver badges105 bronze badges 3- Do you trust the values in the string array or do you need to validate that each value is numeric? – jball Commented Feb 10, 2011 at 16:58
- I was thinking about using split then parseInt to make sure, the values should be ok though – xylar Commented Feb 10, 2011 at 17:01
- If you trust the values, the solution in the first part of @Andy E's answer is the simplest and quickest. – jball Commented Feb 10, 2011 at 17:04
3 Answers
Reset to default 5"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/en/JavaScript/Reference/Global_Objects/Array/map
Array.prototype.map
is in ECMAScript5, so don't be afraid to augment Array.prototype
.
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.
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.
本文标签: javascriptString values to Numeric ArrayStack Overflow
版权声明:本文标题:javascript - String values to Numeric Array - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745169051a2645859.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论