[英]How to safely convert a comma-separated string to an array of numbers
Edit : 编辑 :
This question specifically addresses the problem that empty strings as well as any number of space characters are converted to 0
using Number(str)
. 这个问题专门解决了使用
Number(str)
将空字符串以及任意数量的空格字符转换为0
。
Take a look at the following snippet: 看一下以下片段:
convertBtn.addEventListener('click', () => console.log(toArrayOfNumber(foo.value))) const toArrayOfNumber = str => str.split(',').map(Number);
<input type="text" id="foo" value="1,2,4,-1" /> <button type="button" id="convertBtn">convert to array of numbers</button>
As long as the input has a proper value
everything works fine. 只要输入具有适当的
value
一切正常。 Now I want to make it failsafe for the following values: 现在我想让它对以下值保持安全:
,
, ,,
What caught me off guard here is that Number("")
and Number(" ")
both return 0
(which I don't want as for my usecase I don't want ""
or any number of spaces to be considered a Number
). 让我措手不及的是,
Number("")
和Number(" ")
都返回0
(我不想要我的用例我不想要""
或任意数量的空格被视为Number
)。
So I came up with this: 所以我想出了这个:
convertBtn.addEventListener('click', () => console.log(toArrayOfNumber(foo.value))) const toArrayOfNumber = str => str.split(',').filter(x => x.trim() !== "").map(Number);
<input type="text" id="foo" value="1,2,4,-1,,, ,, 11" /> <button type="button" id="convertBtn">convert to array of numbers</button>
This feels awkward, I'm hoping there is an obvious and better solution which I don't see. 这感觉很尴尬,我希望有一个明显的,更好的解决方案,我没有看到。
Answer from @KendallFrey (who is refusing to post so I'm stealing his solution) 来自@KendallFrey的回答(谁拒绝发帖,所以我偷了他的解决方案)
'1,2,4,-1,,, ,, 11,0,0'.split(/[, ]+/).map(x=>+x)
You can still use .map(Number)
but x=>+x
is 1 byte shorter. 您仍然可以使用
.map(Number)
但x=>+x
缩短1个字节。
Results in the console: (7) [1, 2, 4, -1, 11, 0, 0]
控制台中的结果:
(7) [1, 2, 4, -1, 11, 0, 0]
Another regex solution (that doesn't allow decimals): /-?\\d+/g
另一个正则表达式解决方案(不允许小数):
/-?\\d+/g
If you're only dealing with integers the following will also work. 如果您只处理整数,则以下内容也适用。 0's will be kept but empty values will be removed.
将保留0,但将删除空值。
split(',').filter(num => !isNaN(parseInt(num))).map(Number);
Example 例
const str = '1,2,4,-1,,, ,0, 11'; console.log(str.split(',').filter(num => !isNaN(parseInt(num))).map(Number));
Try this: 试试这个:
const value="-99,1,2,4,-1,,, ,0,, 11" const toArrayOfNumber = str => str.split(',').map(num => num.trim() && Number(num)).filter(num => !Number.isNaN(num) && typeof num != 'string'); const nums = toArrayOfNumber(value); nums.forEach(num => console.log(typeof num, num));
We use the results of trim
to determine if we should process it like a number. 我们使用
trim
的结果来确定我们是否应该像数字一样处理它。 If not then we just have a string
and that is filtered out. 如果没有,那么我们只有一个
string
,并被过滤掉。
You could also do this via Array.reduce
where in each iteration you check with isNaN
for the parseInt
: 您也可以通过
Array.reduce
执行此操作,在每次迭代中,您使用isNaN
检查parseInt
:
let data = "1,2,4,-1,,, ,0, 11" let r = data.split(',').reduce((r,c) => isNaN(parseInt(c)) ? r : [...r, +c],[]) console.log(r)
This way you only iterate over the array once
post splitting. 这样,您只能
iterate over the array once
分割后iterate over the array once
。 Also this would keep zeros intact and just drop any non numbers. 这也将保持零完整,只丢弃任何非数字。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.