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