# 如何在JavaScript中將數組中的所有元素轉換為整數？

## (9)

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

for(var i=0; i<count_array.length;i++) count_array[i] = parseInt(count_array[i], 10);

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但我需要這些值為整數。

1. 它的工作原理是：

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
2. 它更短。

3. 它更快一點， 並利用緩存，當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'! >_<

var arrayOfNumbers = arrayOfStrings.map(Number);

var arrayOfNumbers = _.map(arrayOfStrings, Number);

var arr = ["1", "2", "3"];
arr = arr.map(Number);
console.log(arr); // [1, 2, 3]

for(var i=0, len=count_array.length; i<len; i++){
count_array[i] = parseInt(count_array[i], 10);
}

\$.map(arr, function(val,i) {
return parseInt(val);
});

const arrString = ["1","2","3","4","5"];
const arrInteger = arrString.map(x => Number.parseInt(x, 10));

const arrString = ["1","2","3","4","5"];
const arrInteger = arrString.map(Number.parseInt);

map expect - (value, index, array) ，如parseInt所期望的那樣 - (value, radix)

ECMAScript5為Array提供了一個map方法，將一個函數應用於數組的所有元素。 這是一個例子：

var a = ['1','2','3']
var result = a.map(function (x) {
return parseInt(x, 10);
});

console.log(result);