LadderLay/JavaScript365

['1', '2', '3'].map(parseInt) what & why ?

Opened this issue · 0 comments

考查知识点:JS的映射与解析

解析:

parseInt(string, radix)
当基数radix未指定、undefined、0时,分以下三种情况讨论:

  • string以**'0X'、'0x'**开头 => radix = 16
  • string以**'0'**开头 => radix = 8或10
  • string以其他值开头 => radix = 10

map 中 callback 函数会被自动传入三个参数:数组元素,元素索引,原数组本身。
因此此处parseInt传入参数实际上为(element, index)
['1', '2', '3'].map(parseInt) 可以分步理解为

'1' - map(parseInt('1',0)
'2' - map(parseInt('1',1)
'3' - map(parseInt('1',2)

而2在基数为1的进制中、3在基数为2的进制中均为非法数字,因此均返回NaN
遍历字符串数组的正确写法可以是

//1
['1', '2', '3'].map(Number)
//2
['1', '2', '3'].map(num=>parseInt(num,10))

答案:

常见的错误答案 [1, 2, 3],
实际结果是 [1, NaN, NaN]

参考链接:

题目来源
map
parseInt