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

第 2 题:['1', '2', '3'].map(parseInt) what & why ? #29

Open
Yolo-0317 opened this issue May 20, 2021 · 0 comments
Open

第 2 题:['1', '2', '3'].map(parseInt) what & why ? #29

Yolo-0317 opened this issue May 20, 2021 · 0 comments

Comments

@Yolo-0317
Copy link
Owner

原文:Advanced-Frontend/Daily-Interview-Question#4

parseInt(string, radix)接收两个参数,第一个表示被处理的值(字符串),第二个表示为解析时的基数。

string要被解析的值。如果参数不是一个字符串,则将其转换为字符串(使用 ToString 抽象操作)。字符串开头的空白符将会被忽略。

radix 可选从 2 到 36,表示字符串的基数。例如指定 16 表示被解析值是十六进制数。请注意,10不是默认值!

  • parseInt('1', 0) //radix 为 0 时,且 string 参数不以“0x”和“0”开头时,按照 10 为基数处理。这个时候返回 1;
  • parseInt('2', 1) // 1不是可选,所以NaN
  • parseInt('3', 2) // 基数为 2(2 进制)表示的数中,最大值小于 3,所以无法解析,返回 NaN。

返回NaN情况:

  • radix 小于 2 或大于 36 (radix为0的情况要参考文档里面具体介绍)
  • 第一个非空格字符不能转换为数字。

MDN中有详细解释:

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/parseInt​

Map的MDN:
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/map​

['1', '1', '3'].map(parseInt)
['1', '0', '3'].map(parseInt)
['1', 1, '3'].map(parseInt)
答案都是: [1, NaN, NaN]
​
parseInt('2', 1)
parseInt('1', 1)
这俩都是 NaN
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant