为什么 parseInt returns NaN 与 Array.map 一起使用时?
Why does parseInt returns NaN when used with Array.map?
如果我使用 parseInt
映射一个数组,它 returns 意外和不正确的结果:
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
来源:
如果我使用 parseInt
映射一个数组,它 returns 意外和不正确的结果:
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
来源: