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) 结果是什么? #2

Open
Hanpoung opened this issue May 10, 2019 · 0 comments
Open

第 2 题:['1', '2', '3'].map(parseInt) 结果是什么? #2

Hanpoung opened this issue May 10, 2019 · 0 comments

Comments

@Hanpoung
Copy link
Owner

今天的题目是['1', '2', '3'].map(parseInt)结果是什么?

要知道这道题的结果,首先你得知道map方法和parseInt方法:

MDN是这样描述的

map() 方法创建一个新数组,其结果是该数组中的每个元素都调用一个提供的函数后返回的结果。

parseInt() 函数解析一个字符串参数,并返回一个指定基数的整数 (数学系统的基础)。

更多详情点MDN查看

回到正题,上述题目真正执行的代码是这样的:

['1', '2', '3'].map((item, index) => {
	return parseInt(item, index)
})

所以返回值是这样的

parseInt('1', 0) // 1 如果省略第二个参数或其值为 0,则数字将以 10 为基础来解析
parseInt('2', 1) // NaN 第二个参数小于 2 或者大于 36,则 parseInt() 将返回 NaN
parseInt('3', 2) // NaN 除了“0、1”外,其它数字都不是有效二进制数字

最后答案即为:

['1', '2', '3'].map(parseInt) // 1, NaN, NaN
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant