[1,4,9].map(Math.sqrt)
// [1, 2, 3]
['1','2','3'].map(parseInt)
//預(yù)期 [1, 2, 3]
//結(jié)果 [1, NaN, NaN]
回調(diào)函數(shù)Array.map
有3個(gè)參數(shù) map (當(dāng)前正在遍歷的元素, 元素索引, 原數(shù)組本身)
parseInt
有兩個(gè)參數(shù) parseInt(元素乾胶,進(jìn)制數(shù))涧郊。parseInt
把傳過來的索引值當(dāng)成進(jìn)制數(shù)來使用從而返回了NaN
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
可以寫進(jìn)函數(shù):
['1','2','3'].map(function(num) { return parseInt(num, 10); });
或者使用箭頭函數(shù):
['1','2','3'].map(num => parseInt(num, 10));