JavaScript將數組中的字符串轉變成整數數字使用parseInt時的注意
var arr = ['1', '2', '3']
console.log(arr.map(parseInt))
//打印結果: 1,NaN,NaN
1
2
3
再看另一個例子
var arr = ['10', '10', '10']
console.log(arr.map(parseInt))
//打印結果: 10,NaN,2
1
2
3
此時發現兩個例子打印出不同的結果,產生上面結果的原因是其實map遍歷后打印出的順序是
parseInt('1', 0); // 1
parseInt('2', 1); // NaN
parseInt('3', 2); // NaN
parseInt(‘10', 0); // 10
parseInt(‘10', 1); // NaN
parseInt(‘10', 2); // 2
1
2
3
4
5
6
7
再去看一下MDN的官方文檔說明
兩個例子產生不同結果的具體原因總結為
1’ radix不能超出范圍
2’ 把’3‘看做二進制,返回十進制數不可實現,因為除了0,1外,其它數字都不是有效二進制數字。
兩個例子產生不同結果的具體原因總結為
1’ radix不能超出范圍
2’ 把’3‘看做二進制,返回十進制數不可實現,因為除了0,1外,其它數字都不是有效二進制數字。
現在再來實現將數組中的字符串轉變成整數數字,有以下幾種方法:
第一種方法 (改寫parseInt的用法, 建議每次遍歷時加上radix的數值)
var arr = ['1', '2', '3']
console.log(arr.map(i => parseInt(i, 0)));
第二種方法
var arr = ['1', '2', '3']
console.log(arr.map(i => i * 1));
//或者
console.log(arr.map(i => i / 1));
1
第三種方法
var arr = ['1', '2', '3']
console.log(arr.map(i => Math.floor(i)));
1
2
第四種方法
var arr = ['1', '2', '3']
console.log(arr.map(Number));
1
2
如有錯誤或者缺漏,歡迎指點。
