javascript - 为什么 parseInt 与 Array.map 一起使用时返回 NaN?

标签 javascript arrays ecmascript-6 parseint

如果我使用 parseInt 映射数组它返回意外且不正确的结果:

console.log(["1234-04-23", "1234", "04", "23"].map(parseInt))
// => [1234, NaN, 0, 2]

但多余地添加箭头函数包装器可以按预期工作

console.log(["1234-04-23", "1234", "04", "23"].map(e => parseInt(e)))
// => [1234, 1234, 4, 23]

这两个语句的行为应该相同,那么为什么第一个语句会中断?

最佳答案

因为map添加了第二个和第三个参数:索引和数组本身。请参阅:

["1234-04-23", "1234", "04", "23"].map(console.log);
// => 1234-04-23 0 ["1234-04-23", "1234", "04", "23"]
// => 1234 1 ["1234-04-23", "1234", "04", "23"]
// => 04 2 ["1234-04-23", "1234", "04", "23"]
// => 23 3 ["1234-04-23", "1234", "04", "23"]

正如您在 the specification 中看到的那样, parseInt 还接受第二个参数作为基础,因此您实际上正在这样做:

console.log(["1234-04-23", "1234", "04", "23"].map((e, e2) => parseInt(e, e2)));
// => [1234, NaN, 0, 2]

NaN 是因为:

parseInt stops at the first invalid character and returns whatever it has at that point. If there are no valid characters to parse, it returns NaN

来源:https://stackoverflow.com/a/39147168/1525495

关于javascript - 为什么 parseInt 与 Array.map 一起使用时返回 NaN?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48479663/

相关文章:

javascript - 修改对象数组中的对象值

javascript - 为什么 Chrome 在 "strict mode"中使用 block 内的函数时仍然保持沉默?

javascript - 为用于搜索引擎抓取的 AngularJS 应用程序创建 HTML 快照

javascript - 如果外部加载 JS 文件,Vue 无法注册组件

javascript - 如何为视差运动添加缓动?

javascript - es6 箭头函数在转译为 javascript 后无法识别此运算符

javascript - 从 Tomcat 8.5 启动 Python 脚本

iphone - 如何在 Objective-C 中将字符串转换为数组?

Javascript提示仅读取输入数字的第一位

arrays - 算法 - 查找数组的最佳元素