Files
zhaoguiyang.site/temp_docs/map遍历数字的陷阱.md
joyzhao f8173fd706 feat: migrate and organize documentation and blog posts
refactor(blog): restructure blog post layouts and metadata

docs: add markdown migration guide and project rules update

style(global.css): update typography theme variables

chore: move temp_docs to appropriate blog post locations
2025-06-19 20:24:09 +08:00

1.7 KiB
Raw Blame History

id, title, sidebar_label, description
id title sidebar_label description
map-traversal-traps Map遍历数字的陷阱 map遍历数字的陷阱 Map遍历数字的陷阱,['1','2','3'].map(parseInt)的返回值是什么?

['1','2','3'].map(parseInt)的返回值

先说结果:其运行的结果是: [1, NAN, NAN]

map方法

map()方法会创建一个新数组,其结果是该数组中的每个元素都调用一个提供的回调函数的返回值

let arr = [ 1, 2, 3 ];

arr.map ( ( item, index, arr ) => item ) // 1, 2, 3 [ 1, 2, 3 ]

该函数接收三个参数:当前项, 下标索引, 操作的数组

parsetInt方法

parseInt() 是用来解析字符串使字符串成为指定基数的整数parseInt的基本语法:

parseInt(string, radix)

接收两个参数第一个表示被处理的值字符串第二个表示为解析时的基数。radix是一个介于2-36之间的整数返回解析后的整数值。 如果被解析参数的第一个字符无法被转化成数值类型,则返回 NaN

praseInt('111') // 111

parseInt('111', 0) // 111 

// radix为0时且string参数不以"0x"和"0"开头时按照10为基数处理

parseInt('111', 1) // NaN 【2 <= radix <= 36】

parseInt('111', 2) // 7

结论

当运行 [1, 2, 3].map(parseInt) 上时实际上运行的是:

['1', '2', '3'],map( parseInt('1', 0)); // radix为0时使用默认的10进制。

['1', '2', '3'],map( parseInt('2', 0)); // radix值在2-36无法解析返回NaN

['1', '2', '3'],map( parseInt('3', 0)); // 基数为22进制数表示的数中最大值小于3无法解析返回NaN

map函数返回的是一个数组所以最后结果为[1, NaN, NaN]