问题
写出输出结果
console.log([1, 2, 3, 4].map(parseInt))
输出结果:
1,NaN, NaN, NaN
考察知识
1、map
var new_array = arr.map(function callback(currentValue[, index[, array]]) {
// 新数组的返回元素
}[, thisArg])
参数:
callback:数组迭代的每一项执行的回调函数,可以有三个参数:
currentValue:当前迭代项
index:当前迭代项的索引 (可选)
array: map 方法调用的数组(可选)
thisObject:在执行回调函数时定义的 this 对象(没有传递或者为 null,将会使用全局对象)。
2、parseInt
parseInt(string, radix);
解析一个字符串并返回指定基数的十进制整数, 或者NaN
返回NaN的情况:
1. radix 小于 2 或大于 36
2. 第一个非空格字符不能转换为数字。
以上代码相当于执行了
let res = [1, 2, 3, 4].map((item, index, array)=>{
return parseInt(item, index);
})
console.log(res);
// [ 1, NaN, NaN, NaN ]
正确的用法
let res = [1, 2, 3, 4].map((item)=>{
return parseInt(item);
})
console.log(res);
// [ 1, 2, 3, 4 ]
举一反三
var arr = [10, 18, 0, 10, 42, 23]
arr = arr.map(parseInt)
console.log(arr)
// [ 10, NaN, 0, 3, NaN, 13 ]
[参考] 透过网红面试题,超级详细的解析parseInt,学不懂找我