如何在JavaScript中将逗号分隔的字符串转换为数值数组 [英] How to convert comma separated string into numeric array in javascript
问题描述
我在JavaScript中有一个一维整数数组,我想从逗号分隔的字符串中添加数据,有没有简单的方法呢?
I have a one-dimensional array of integer in JavaScript that I'd like to add data from comma separated string, Is there a simple way to do this?
例如:var strVale = "130,235,342,124 ";
推荐答案
You can use split() to get string array from comma separated string. If you iterate and perform mathematical operation on element of string array then that element will be treated as number by run-time cast but still you have string array. To convert comma separated string int array see the edit.
arr = strVale.split(',');
var strVale = "130,235,342,124";
arr = strVale.split(',');
for(i=0; i < arr.length; i++)
console.log(arr[i] + " * 2 = " + (arr[i])*2);
输出
130 * 2 = 260
235 * 2 = 470
342 * 2 = 684
124 * 2 = 248
编辑,用逗号分隔的字符串转换为int数组在上面的示例中,字符串被强制转换为表达式中的数字,但是要从字符串数组中获取int数组,您需要将其转换为数字.
Edit, Comma separated string to int Array In the above example the string are casted to numbers in expression but to get the int array from string array you need to convert it to number.
var strVale = "130,235,342,124";
var strArr = strVale.split(',');
var intArr = [];
for(i=0; i < strArr.length; i++)
intArr.push(parseInt(strArr[i]));
这篇关于如何在JavaScript中将逗号分隔的字符串转换为数值数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!