javascript Map、parseInt 的奇怪行为

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14528397/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 21:52:08  来源:igfitidea点击:

Strange behavior for Map, parseInt

javascriptfunctional-programming

提问by Ben McCormick

Possible Duplicate:
javascript - Array.map and parseInt

可能重复:
javascript - Array.map 和 parseInt

I saw this example of strange JavaScript behavior on twitter

在 twitter 上看到了这个奇怪的 JavaScript 行为的例子

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

evaluates to

评估为

[10, NaN, 2, 3, 4]

could somebody explain this behavior? I verified it in chrome and firebug

有人可以解释这种行为吗?我在 chrome 和 firebug 中验证过

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

correctly returns an array of 10s as integers. Is this an improper use of map(), a bug with parseInt, or something else?

正确返回一个 10s 的数组作为整数。这是对 map() 的不当使用、parseInt 的错误还是其他什么?

回答by VisioN

parseIntreceives two arguments: string and radix:

parseInt接收两个参数:字符串和基数:

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

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

while maphandler's second argument is index:

map处理程序的第二个参数是索引:

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

...回调使用三个参数调用:元素的值、元素的索引和正在遍历的 Array 对象。

回答by Joseph Silber

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

parseInt使用 map 传入的前两个参数,并使用第二个参数指定基数。

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.

这是 MDN 的链接parseInthttps: //developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/parseInt

回答by Justin Niessner

From MDN:

来自 MDN:

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

callback 使用三个参数调用:元素的值、元素的索引和被遍历的 Array 对象。

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

parseInt()需要两个参数。值和基数。这意味着parseInt()正在使用意外参数调用该函数。