简体   繁体   English

如何将一串逗号分隔的数字转换为整数?

[英]How to convert a string of comma separated numbers to integers?

I have an array of values such that arr = [108, 109] .我有一个值数组,例如arr = [108, 109] I then converted them to a string using arr.toString() , thus getting "108, 109" .然后我使用arr.toString()将它们转换为字符串,从而得到"108, 109" The reason I did this was because my API required that this parameter arr asked for an array to string conversion.我这样做的原因是因为我的 API 要求此参数 arr 要求将数组转换为字符串。 How can I turn this value into an integer?如何将此值转换为 integer?

I tried doing const test = parseInt(arr) but I only get 108 .我尝试做const test = parseInt(arr)但我只得到108 Why is that?这是为什么? I essentially just want the values 108, 109 .我基本上只想要值108, 109

First split the values with comma using the split() method like this.首先使用像这样的split()方法用逗号分割值。

arr.split(',')

After that you will get each value separated in an array which will be accessible by giving array index.之后,您将在一个数组中分隔每个值,该数组可以通过提供数组索引来访问。 So arr[0] will include 108 and arr[1] will include 109. Now all that's left to do is parse them individually.所以arr[0]将包括 108 而arr[1]将包括 109。现在剩下要做的就是单独解析它们。

parseInt(arr[0]) 
parseInt(arr[1]) 

The reason you are getting 108 is due to parseInt() stopping after any invalid outcome.您得到108的原因是由于parseInt()在任何无效结果后停止。 So what you are basically trying to to is:所以你基本上想要的是:

parseInt('108, 109');

which stops at the comma.停在逗号处。

In case you need the whole array I suggest using split() together with map() .如果您需要整个数组,我建议将split()map() ) 一起使用。

 const test = '108, 109'.split(',').map(Number); console.log(test)

the values 108 and 109 are different, so you have to parseInt them separately by doing parseInt("108") and parseInt("109")值 108 和 109 不同,因此您必须通过执行parseInt("108")parseInt("109")分别parseInt它们

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM