# 为什么parseInt用Array＃map产生NaN？

2020/10/05 05:41 · javascript ·  · 0评论
``````[1,4,9].map(Math.sqrt)
``````

``````[1,2,3]
``````

``````['1','2','3'].map(parseInt)
``````

``````[1, NaN, NaN]
``````

``````['1','2','3'].map(function(i){return +i;}) // returns [1,2,3]
``````

``````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
``````

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

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

（在两种情况下，最好如图所示显式提供一个基数`parseInt`，因为否则它会根据输入来猜测基数。在某些较旧的浏览器中，前导0导致它猜测八进制，这往往是有问题的。它将仍然存在问题。如果字符串以`0x`开头，则猜测为十六进制。）

`map`正在传递第二个参数，该参数（在许多情况下）弄乱了`parseInt`radix参数。

`['10','1','100'].map(_.partial(parseInt, _, 10))`

`['10','1','100'].map(function(x) { return parseInt(x, 10); });`

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

console.log(a);``````

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

``````//  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 ) } );
``````

``````[10, 20, 30].map(x => parseInt(x))
``````

``````[10, 20, 30].map(x => parseInt(x, 10))
``````

``````var parseInt10 = function(x){return parseInt(x, 10);}

['0', '1', '2', '10', '15', '57'].map(parseInt10);
//[0, 1, 2, 10, 15, 57]
``````

`parseInt`为此，应避免恕我直言。您可以包装它以使其在以下情况下更安全：

``````const safe = {
parseInt: (s, opt) => {
const { radix = 10 } = opt ? opt : {};
}
}

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

lodash / fp默认将iteratee参数设置为1，以避免这些陷阱。我个人发现这些变通办法可以创建尽可能多的错误。`parseInt`我认为将黑名单推荐给更安全的实现是一种更好的方法。