如何将一串数字转换为一组数字? [英] How to convert a string of numbers to an array of numbers?
本文介绍了如何将一串数字转换为一组数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下字符串 -
var a = "1,2,3,4";
当我这样做 -
var b = a.split(',');
我得到 b
作为 ["1", "2", "3", "4"]
我可以做些什么让 b
变成 [1, 2, 3, 4]
吗?
can I do something to get b
as [1, 2, 3, 4]
?
推荐答案
我给高尔夫球手的 2 美分:
My 2 cents for golfers:
b="1,2,3,4".split`,`.map(x=>+x)
backquote 是字符串字面量所以我们可以省略括号(因为 split 函数的性质)但它等价于 split(',')
.字符串现在是一个数组,我们只需要使用返回字符串整数的函数来映射每个值,所以 x=>+x
(甚至比 Number
函数(5 个字符而不是 6 个字符)等价于:
backquote is string litteral so we can omit the parenthesis (because of the nature of split function) but it is equivalent to split(',')
. The string is now an array, we just have to map each value with a function returning the integer of the string so x=>+x
(which is even shorter than the Number
function (5 chars instead of 6)) is equivalent to :
function(x){return parseInt(x,10)}// version from techfoobar
(x)=>{return parseInt(x)} // lambda are shorter and parseInt default is 10
(x)=>{return +x} // diff. with parseInt in SO but + is better in this case
x=>+x // no multiple args, just 1 function call
我希望它更清楚一点.
这篇关于如何将一串数字转换为一组数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文