Why does parseInt yield NaN with Array#map?

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

    The callback function in Array.map has three parameters:

    From the same Mozilla page that you linked to:

    callback is invoked with three arguments: the value of the element, the index of the element, and the Array object being traversed."

    So if you call a function parseInt which actually expects two arguments, the second argument will be the index of the element.

    In this case, you ended up calling parseInt with radix 0, 1 and 2 in turn. The first is the same as not supplying the parameter, so it defaulted based on the input (base 10, in this case). Base 1 is an impossible number base, and 3 is not a valid number in base 2:

    parseInt('1', 0); // OK - gives 1
    parseInt('2', 1); // FAIL - 1 isn't a legal radix
    parseInt('3', 2); // FAIL - 3 isn't legal in base 2 
    

    So in this case, you need the wrapper function:

    ['1','2','3'].map(function(num) { return parseInt(num, 10); });
    

    or with ES2015+ syntax:

    ['1','2','3'].map(num => parseInt(num, 10));
    

    (In both cases, it's best to explicitly supply a radix to parseInt as shown, because otherwise it guesses the radix based on the input. In some older browsers, a leading 0 caused it to guess octal, which tended to be problematic. It will still guess hex if the string starts with 0x.)

提交回复
热议问题