Why does parseInt yield NaN with Array#map?

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

    You could solve this problem using Number as iteratee function:

    var a = ['0', '1', '2', '10', '15', '57'].map(Number);
    
    console.log(a);

    Without the new operator, Number can be used to perform type conversion. However, it differs from parseInt: it doesn't parse the string and returns NaN if the number cannot be converted. For instance:

    console.log(parseInt("19asdf"));
    console.log(Number("19asf"));

提交回复
热议问题