Javascript 将字符串转换为整数数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4291447/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
convert string into array of integers
提问by xer0x
I want to convert the following string '14 2'
into an array of two integers.
How can I do it ?
我想将以下字符串'14 2'
转换为两个整数的数组。我该怎么做 ?
采纳答案by Nick Craver
You can .split()
to get an array of strings, then loop through to convert them to numbers, like this:
您可以.split()
获取一个字符串数组,然后循环将它们转换为数字,如下所示:
var myArray = "14 2".split(" ");
for(var i=0; i<myArray.length; i++) { myArray[i] = +myArray[i]; }
//use myArray, it's an array of numbers
The +myArray[i]
is just a quick way to do the number conversion, if you're sure they're integers you can just do:
这+myArray[i]
只是进行数字转换的一种快速方法,如果您确定它们是整数,您可以这样做:
for(var i=0; i<myArray.length; i++) { myArray[i] = parseInt(myArray[i], 10); }
回答by xer0x
A quick one for modern browsers:
适用于现代浏览器的快速浏览器:
'14 2'.split(' ').map(Number);
// [14, 2]`
回答by Todd
SO...older thread, I know, but...
所以......旧线程,我知道,但是......
EDIT
编辑
@RoccoMusolino had a nice catch; here's an alternative:
@RoccoMusolino 有一个不错的收获;这是一个替代方案:
TL;DR:
特尔;博士:
const intArray = [...("5 6 7 69 foo 0".split(' ').filter(i => /\d/g.test(i)))]
WRONG: "5 6 note this foo".split(" ").map(Number).filter(Boolean); // [5, 6]
错误:"5 6 note this foo".split(" ").map(Number).filter(Boolean); // [5, 6]
There is a subtle flaw in the more elegant solutions listed here, specifically @amillara and @Marcus' otherwise beautiful answers.
这里列出的更优雅的解决方案有一个微妙的缺陷,特别是@amillara 和@Marcus 的其他漂亮的答案。
The problem occurs when an element of the string array isn't integer-like, perhaps in a case without validation on an input. For a contrived example...
当字符串数组的元素不是整数时,可能会在没有对输入进行验证的情况下出现问题。对于一个人为的例子......
The problem:
问题:
var effedIntArray = "5 6 7 69 foo".split(' ').map(Number); // [5, 6, 7, 69, NaN]
Since you obviously want a PURE int array, that's a problem. Honestly, I didn't catch this until I copy-pasted SO code into my script... :/
由于您显然想要一个 PURE int 数组,这是一个问题。老实说,直到我将 SO 代码复制粘贴到我的脚本中时,我才发现这一点......:/
The(slightly-less-baller)fix:
的(略少-控球)修正:
var intArray = "5 6 7 69 foo".split(" ").map(Number).filter(Boolean); // [5, 6, 7, 69]
So, now even when you have crap int string, your output is a pure integer array. The others are really sexy in most cases, but I did want to offer my mostly rambly w'actually. It is still a one-liner though, to my credit...
所以,现在即使你有垃圾整数字符串,你的输出也是一个纯整数数组。在大多数情况下,其他人真的很性感,但我确实想提供我最随意的w'actually。尽管如此,它仍然是一个单线,我的功劳......
Hope it saves someone time!
希望它可以节省某人的时间!
回答by amillara
var result = "14 2".split(" ").map(function(x){return parseInt(x)});
回答by Yann Rolland
An alternative to Tushar Gupta answer would be :
Tushar Gupta 答案的替代方法是:
'14 2'.split(' ').map(x=>+x);
// [14, 2]`
In code golf you save 1 character. Here the "+" is "unary plus" operator, works like parseInt.
在代码高尔夫中,您可以保存 1 个字符。这里的“+”是“一元加”运算符,作用类似于 parseInt。
回答by ankhzet
The point against parseInt
-approach:
反对parseInt
-approach 的观点:
There's no need to use lambdas and/or give radix
parameter to parseInt
, just use parseFloat
or Number
instead.
不需要使用 lambdas 和/或给radix
参数给parseInt
,只需使用parseFloat
或Number
代替。
Reasons:
原因:
It's working:
var src = "1,2,5,4,3"; var ids = src.split(',').map(parseFloat); // [1, 2, 5, 4, 3] var obj = {1: ..., 3: ..., 4: ..., 7: ...}; var keys= Object.keys(obj); // ["1", "3", "4", "7"] var ids = keys.map(parseFloat); // [1, 3, 4, 7] var arr = ["1", 5, "7", 11]; var ints= arr.map(parseFloat); // [1, 5, 7, 11] ints[1] === "5" // false ints[1] === 5 // true ints[2] === "7" // false ints[2] === 7 // true
It's shorter.
It's a tiny bit quickier and takes advantage of cache, when
parseInt
-approach - doesn't:// execution time measure function // keep it simple, yeah? > var f = (function (arr, c, n, m) { var i,t,m,s=n(); for(i=0;i++<c;)t=arr.map(m); return n()-s }).bind(null, "2,4,6,8,0,9,7,5,3,1".split(','), 1000000, Date.now); > f(Number) // first launch, just warming-up cache > 3971 // nice =) > f(Number) > 3964 // still the same > f(function(e){return+e}) > 5132 // yup, just little bit slower > f(function(e){return+e}) > 5112 // second run... and ok. > f(parseFloat) > 3727 // little bit quicker than .map(Number) > f(parseFloat) > 3737 // all ok > f(function(e){return parseInt(e,10)}) > 21852 // awww, how adorable... > f(function(e){return parseInt(e)}) > 22928 // maybe, without '10'?.. nope. > f(function(e){return parseInt(e)}) > 22769 // second run... and nothing changes. > f(Number) > 3873 // and again > f(parseFloat) > 3583 // and again > f(function(e){return+e}) > 4967 // and again > f(function(e){return parseInt(e,10)}) > 21649 // dammit 'parseInt'! >_<
它正在工作:
var src = "1,2,5,4,3"; var ids = src.split(',').map(parseFloat); // [1, 2, 5, 4, 3] var obj = {1: ..., 3: ..., 4: ..., 7: ...}; var keys= Object.keys(obj); // ["1", "3", "4", "7"] var ids = keys.map(parseFloat); // [1, 3, 4, 7] var arr = ["1", 5, "7", 11]; var ints= arr.map(parseFloat); // [1, 5, 7, 11] ints[1] === "5" // false ints[1] === 5 // true ints[2] === "7" // false ints[2] === 7 // true
它更短。
当
parseInt
-approach - 不这样做时,它会更快一点并利用缓存:// execution time measure function // keep it simple, yeah? > var f = (function (arr, c, n, m) { var i,t,m,s=n(); for(i=0;i++<c;)t=arr.map(m); return n()-s }).bind(null, "2,4,6,8,0,9,7,5,3,1".split(','), 1000000, Date.now); > f(Number) // first launch, just warming-up cache > 3971 // nice =) > f(Number) > 3964 // still the same > f(function(e){return+e}) > 5132 // yup, just little bit slower > f(function(e){return+e}) > 5112 // second run... and ok. > f(parseFloat) > 3727 // little bit quicker than .map(Number) > f(parseFloat) > 3737 // all ok > f(function(e){return parseInt(e,10)}) > 21852 // awww, how adorable... > f(function(e){return parseInt(e)}) > 22928 // maybe, without '10'?.. nope. > f(function(e){return parseInt(e)}) > 22769 // second run... and nothing changes. > f(Number) > 3873 // and again > f(parseFloat) > 3583 // and again > f(function(e){return+e}) > 4967 // and again > f(function(e){return parseInt(e,10)}) > 21649 // dammit 'parseInt'! >_<
Notice: In Firefox parseInt
works about 4 times faster, but still slower than others. In total: +e
< Number
< parseFloat
< parseInt
注意:在 Firefox 中的parseInt
运行速度大约快 4 倍,但仍然比其他的慢。总计:+e
< Number
< parseFloat
<parseInt
回答by Marcus Whybrow
First split the string on spaces:
首先在空格上拆分字符串:
var result = '14 2'.split(' ');
Then convert the result array of strings into integers:
然后将字符串的结果数组转换为整数:
for (var i in result) {
result[i] = parseInt(result[i], 10);
}
回答by ocodo
Just for fun I thought I'd throw a forEach(f())
solution in too.
只是为了好玩,我想我也会提出一个forEach(f())
解决方案。
var a=[];
"14 2".split(" ").forEach(function(e){a.push(parseInt(e,10))});
// a = [14,2]
回答by Ahmed Said
let idsArray = ids.split(',').map((x) => parseInt(x));
回答by Ravi Gaur
Better one line solution:
更好的一行解决方案:
var answerInt = [];
var answerString = "1 2 3 4";
answerString.split(' ').forEach(function (item) {
answerInt.push(parseInt(item))
});