Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
lvwxx opened this issue Jul 23, 2019 · 0 comments
Open

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

lvwxx opened this issue Jul 23, 2019 · 0 comments
Labels
basic JavaScript basic knowledge must konw question Further information is requested

Comments

@lvwxx
Copy link
Owner

lvwxx commented Jul 23, 2019

output

[1, NaN, NaN]

分析

map

  • map 方法创建一个新数组,其结果是该数组中的每个元素都调用一个提供的 callback 后返回的结果。
  • map 函数接受 2 个参数,callback 和 thisArg。
  • callback 函数自动接受 3 个参数,分别是数组当前正在处理的元素、数组当前正在处理元素索引和数组本身。
  • callback 没有指定参数时,默认自动传入上述 3 个参数。
  • thisArg 参数指定 callback 执行时 this 的指向。 没有指定时默认指向 window。

parseInt

  • parseInt 函数接受 2 个参数, 要被解析的值和基数,基数不存在时,默认10进制解析。

结论

parseInt 作为 callback 参数传入map函数后,由于 parseInt 可以接受 2 个参数,所以会收到元素值和元素索引 2 个参数。

所以实际执行的 callback 如下:

parseInt(1,0) // 1
parseInt(2,1) // NaN
parseInt(3,2) // NaN
@lvwxx lvwxx added basic JavaScript basic knowledge must konw question Further information is requested labels Aug 8, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
basic JavaScript basic knowledge must konw question Further information is requested
Projects
None yet
Development

No branches or pull requests

1 participant