<分区>
Possible Duplicate:
javascript - Array.map and parseInt
我偶然发现了以下代码片段:
> ['10','10','10','10','10'].map(parseInt);
[10, NaN, 2, 3, 4]
这里发生了什么?
标签 javascript
<分区>
Possible Duplicate:
javascript - Array.map and parseInt
我偶然发现了以下代码片段:
> ['10','10','10','10','10'].map(parseInt);
[10, NaN, 2, 3, 4]
这里发生了什么?
最佳答案
首先查阅 Array.prototype.map 的文档.关键是这一行:
callback is invoked with three arguments: the value of the element, the index of the element, and the Array object being traversed.
(强调我的)
然后检查 parseInt 的文档:
The parseInt function converts its first argument to a string, parses it, and returns an integer or NaN. If not NaN, the returned value will be the decimal integer representation of the first argument taken as a number in the specified radix (base). For example, a radix of 10 indicates to convert from a decimal number, 8 octal, 16 hexadecimal, and so on. For radices above 10, the letters of the alphabet indicate numerals greater than 9. For example, for hexadecimal numbers (base 16), A through F are used.
和:
If radix is undefined or 0, JavaScript assumes the following:
If the input string begins with "0x" or "0X", radix is 16 (hexadecimal).
If the input string begins with "0", radix is eight (octal). This feature is non-standard, and some implementations deliberately do not support it (instead using the radix 10). For this reason always specify a radix when using parseInt.
If the input string begins with any other value, the radix is 10 (decimal).
所以第一个调用是:
parseInt('10',0, ['10','10',...]) // => 10 (because radix=0)
第二个是:
parseInt('10',1, ['10','10',...]) // => NaN because radix is 1
第三个:
parseInt('10',2, ['10','10',...]) // => 2 because 10 in binary is the number "2"
等等。
关于javascript - parseInt 有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14535242/
相关文章:
javascript - 在 php 中从网站 Facebook 共享
JavaScript 数组不使用 Ajax 发布到 PHP 文件
javascript - MVC - 根据下拉列表显示或隐藏 (div) 字段
php - 为 iSpeech 创建 Send-to Hook
javascript - 为什么不能在vue模板中使用window?
javascript - 如何让Access Control Header跨域访问远程API?
javascript - 当我将 jquery 添加到我的网站时,我的 JS 不起作用