Map、 parseInt 的奇怪行为

可能的复制品:
Javascript-Array.map 和 parseInt

我看到了这个奇怪的 JavaScript 行为 在推特上的例子

['10','10','10','10','10'].map(parseInt)

评估为

[10, NaN, 2, 3, 4]

有人能解释一下这种行为吗? 我用铬合金和纵火犯验证过了

['10','10','10','10','10'].map(function(x){return parseInt(x);})

正确地返回一个10为整数的数组。这是 map ()、 parseInt 错误或其他错误的不当使用吗?

15369 次浏览

parseInt uses the first two arguments being passed in by map, and uses the second argument to specify the radix.

Here's what's happening in your code:

parseInt('10', 0) // 10
parseInt('10', 1) // NaN
parseInt('10', 2) // 2
parseInt('10', 3) // 3
parseInt('10', 4) // 4

Here's a link to MDN on parseInt: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/parseInt.

parseInt receives two arguments: string and radix:

var intValue = parseInt(string[, radix]);

while map handler's second argument is index:

... callback is invoked with three arguments: the value of the element, the index of the element, and the Array object being traversed.

From MDN:

callback is invoked with three arguments: the value of the element, the index of the element, and the Array object being traversed.

parseInt() takes two arguments. The value and the radix. That means that the parseInt() function is being called with unintended parameters.