JavaScript:使用Array.map解析parseInt的基础之谜 [英] JavaScript: parseInt's radix mystery with Array.map

查看:72
本文介绍了JavaScript:使用Array.map解析parseInt的基础之谜的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我执行以下语句时:

var string = "1 1 1 1 1 1 0 1 1"
console.log(string)
var strings = string.split(" ")
console.log(strings)
var numbers1 = strings.map(parseInt)
console.log(numbers1)
var numbers2 = strings.map(function(i){ return parseInt(i, 10) })
console.log(numbers2)

我在控制台中得到以下输出:

I get the following output in the console:

1 1 1 1 1 1 0 1 1
["1", "1", "1", "1", "1", "1", "0", "1", "1"]
[1, NaN, 1, 1, 1, 1, 0, 1, 1]
[1, 1, 1, 1, 1, 1, 0, 1, 1]

我想知道为什么 number1中的第二个元素是NaN。除了这个之外,为什么它适用于所有其他元素呢?

I wonder why the second element in numbers1 is NaN. Why does it work on all the other elements except this one?

推荐答案

这是因为 map 传递其他参数。

It is because map passes additional arguments.

Array.prototype.map = function(currentValue, index, array)

因此当它在索引1时,它将1作为基数传递。

So when it is at index 1, it passes 1 as the radix.

这篇关于JavaScript:使用Array.map解析parseInt的基础之谜的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆