如何在 JavaScript 中将数组中的所有元素转换为整数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4437916/
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
How to convert all elements in an array to integer in JavaScript?
提问by Mohan Ram
I am getting an array after some manipulation. I need to convert all array values as integers.
经过一些操作,我得到了一个数组。我需要将所有数组值转换为整数。
My sample code
我的示例代码
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
now contains 1,2,3,4
but I need these value to be in integers.
count_array
现在包含1,2,3,4
但我需要这些值是整数。
I had used parseInt(count_array);
, but it fails. JS considers each value in this array as string.
我曾经使用过parseInt(count_array);
,但它失败了。JS 将此数组中的每个值视为字符串。
采纳答案by Nick Craver
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);
回答by dheerosaur
ECMAScript5 provides a map
method for Array
s, applying a function to all elements of an array.
Here is an example:
ECMAScript5map
为Array
s提供了一种方法,将函数应用于数组的所有元素。下面是一个例子:
var a = ['1','2','3']
var result = a.map(function (x) {
return parseInt(x, 10);
});
console.log(result);
For more information, check https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/map
有关更多信息,请查看https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/map
回答by Jonas Anseeuw
You can do
你可以做
var arrayOfNumbers = arrayOfStrings.map(Number);
For older browsers which do not support Array.map, you can use Underscore
对于旧的浏览器不支持Array.map,您可以使用下划线
var arrayOfNumbers = _.map(arrayOfStrings, Number);
回答by chzwzrd
var arr = ["1", "2", "3"];
arr = arr.map(Number);
console.log(arr); // [1, 2, 3]
回答by álvaro González
Just loop the array and convert items:
只需循环数组并转换项目:
for(var i=0, len=count_array.length; i<len; i++){
count_array[i] = parseInt(count_array[i], 10);
}
Don't forget the second argument for parseInt.
不要忘记 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 Rithik Singh
var inp=readLine();//reading the input as one line string
var nums=inp.split(" ").map(Number);//making an array of numbers
console.log(nums);`
input : 1 9 0 65 5 7 output:[ 1, 9, 0, 65, 5, 7 ]
输入:1 9 0 65 5 7 输出:[ 1, 9, 0, 65, 5, 7 ]
what if we dont use .map(Number)
如果我们不使用怎么办 .map(Number)
code
代码
var inp=readLine();//reading the input as one line string
var nums=inp.split(" ");//making an array of strings
console.log(nums);
input : 1 9 0 65 5 7 output:[ '1', '9', '0', '65', '5', '7']
输入:1 9 0 65 5 7 输出:['1', '9', '0', '65', '5', '7']
回答by Juanma Menendez
If you want to convert an Array of digits to a single number just use:
如果要将数字数组转换为单个数字,请使用:
Number(arrayOfDigits.join(''));
Example
例子
const arrayOfDigits = [1,2,3,4,5];
const singleNumber = Number(arrayOfDigits.join(''));
console.log(singleNumber); //12345
回答by Mohan Ram
const arrString = ["1","2","3","4","5"];
const arrInteger = arrString.map(x => Number.parseInt(x, 10));
Above one should be simple enough,
上面一个应该够简单了,
One tricky part is when you try to use point free function for mapas below
一个棘手的部分是当您尝试对地图使用无点功能时,如下所示
const arrString = ["1","2","3","4","5"];
const arrInteger = arrString.map(Number.parseInt);
In this case, result will be [1, NaN, NaN, NaN, NaN]
since function argument signature for map
and parseInt
differs
在这种情况下,结果将是[1, NaN, NaN, NaN, NaN]
因为函数参数签名为map
和parseInt
不同
map expects -
(value, index, array)
where as parseInt expects -(value, radix)
地图期望 -
(value, index, array)
parseInt 期望 -(value, radix)
回答by nitzan
Using jQuery, you can like the map()
methodlike so;
使用jQuery,你可以喜欢这样的map()
方法;
$.map(arr, function(val,i) {
return parseInt(val);
});