Why does parseInt yield NaN with Array#map?

前端 未结 7 1471
故里飘歌
故里飘歌 2020-11-21 11:29

From the Mozilla Developer Network:

[1,4,9].map(Math.sqrt)

will yield:

[1,2,3]

Why then does this:

<
7条回答
  •  悲哀的现实
    2020-11-21 11:45

    parseInt IMHO should be avoided for this very reason. You can wrap it to make it more safe in these contexts like this:

    const safe = {
      parseInt: (s, opt) => {
        const { radix = 10 } = opt ? opt : {};
        return parseInt(s, radix);
      }
    }
    
    console.log( ['1','2','3'].map(safe.parseInt) );
    console.log(
      ['1', '10', '11'].map(e => safe.parseInt(e, { radix: 2 }))
    );

    lodash/fp caps iteratee arguments to 1 by default to avoid these gotchas. Personally I have found these workarounds to create as many bugs as they avoid. Blacklisting parseInt in favor of a safer implementation is, I think, a better approach.

提交回复
热议问题