Why does parseInt yield NaN with Array#map?

前端 未结 7 1484
故里飘歌
故里飘歌 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:44

    I'm going to wager that it's something funky going on with the parseInt's 2nd parameter, the radix. Why it is breaking with the use of Array.map and not when you call it directly, I do not know.

    //  Works fine
    parseInt( 4 );
    parseInt( 9 );
    
    //  Breaks!  Why?
    [1,4,9].map( parseInt );
    
    //  Fixes the problem
    [1,4,9].map( function( num ){ return parseInt( num, 10 ) } );
    

提交回复
热议问题