如何在JavaScript中将数组中的所有元素转换为整数? [英] How to convert all elements in an array to integer in JavaScript?
本文介绍了如何在JavaScript中将数组中的所有元素转换为整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
经过一些操作后我得到了一个数组。我需要将所有数组值转换为整数。
I am getting an array after some manipulation. I need to convert all array values as integers.
我的示例代码
var result_string = 'a,b,c,d|1,2,3,4';
result = result_string.split("|");
alpha = result[0];
count = result[1];
// console.log(alpha);
// console.log(count);
count_array = count.split(",");
count_array
现在包含 1,2,3,4
但我需要这些值为整数。
count_array
now contains 1,2,3,4
but I need these value to be in integers.
我用过 parseInt (count_array);
,但它失败了。 JS将此数组中的每个值都视为字符串。
I had used parseInt(count_array);
, but it fails. JS considers each value in this array as string.
推荐答案
您需要遍历并解析/转换数组中的元素,像这样:
You need to loop through and parse/convert the elements in your array, like this:
var result_string = 'a,b,c,d|1,2,3,4',
result = result_string.split("|"),
alpha = result[0],
count = result[1],
count_array = count.split(",");
for(var i=0; i<count_array.length;i++) count_array[i] = +count_array[i];
//now count_array contains numbers
You can test it out here. If the +
, is throwing, think of it as:
for(var i=0; i<count_array.length;i++) count_array[i] = parseInt(count_array[i], 10);
这篇关于如何在JavaScript中将数组中的所有元素转换为整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文