map Feeds parseInt The Index As Radix
map passes (element, index, array) to callbacks, so parseInt treats the index as a radix and returns NaN; wrap it or call Number instead.
Code
// map 把 (element, index, array) 传给回调:parseInt 把 index 当成进制
console.log(["1", "2", "3"].map(parseInt));
// 修正:箭头函数只透传一个参数
console.log(["1", "2", "3"].map((value) => parseInt(value)));
// 解析 16 进制:显式进制让 "1f" 这类值正确转换
console.log(["10", "1f"].map((value) => parseInt(value, 16)));
// Number() 更省心:只接收一个参数,不会被 index 污染
console.log(["1", "2", "3"].map(Number));
// parseFloat 只接受一个参数:多余的 index 被忽略,结果正常
console.log(["1", "2", "3"].map(parseFloat));
// 需要丢弃非法值:flatMap 过滤一次即可
console.log(
["1", "x", "3"].flatMap((value) => (Number.isNaN(Number(value)) ? [] : [Number(value)])),
);Output
Captured from a sandboxed run of this snippet in the build pipeline.
[ 1, NaN, NaN ]
[ 1, 2, 3 ]
[ 16, 31 ]
[ 1, 2, 3 ]
[ 1, 2, 3 ]
[ 1, 3 ]Points of care
- Nothing to vet in a supply-chain review — the file pulls in no packages.
- One load-bearing line from the snippet:
["1", "x", "3"].flatMap((value) => (Number.isNaN(Number(value)) ? [] : [Number(value)])),
Interactive Tools for This Topic
FAQ
- Are there third-party dependencies?
- No. The dependency list is empty; the code stays inside the standard library.
Report a problem with this exampleOpens a pre-filled issue on GitHub.