2017-07-19 67 views
1

我在讀博客時指出_.parseInt是安全的。 根據文檔,它也接受作爲本地parseInt所做的第二個參數的基數。 通常在映射數組時,直接將parseInt傳遞給映射時,可能會遇到意外的行爲。lodash的_.parseInt如何在地圖上安全地解析

lodash的parseInt如何安全工作?

var a = ['2', '3', '4', '5', '6', '7', '8'] 

//case 1:  
_.map(a, parseInt) 
//[2, NaN, NaN, NaN, NaN, NaN, NaN] - this is the expected output 

//case 2:  
_.map(a, (num, index) => _.parseInt(num, index)) 
//[2, NaN, NaN, NaN, NaN, NaN, NaN] - this is the expected output 

//case 3:  
_.map(a, _.parseInt) 
//[2, 3, 4, 5, 6, 7, 8] - how is this working correctly? 

情況2與情況3的區別是什麼?

回答

1

The implementation對​​採取「祕密」第三的說法。

如果提供了第三個參數,如_.map(a, _.parseInt)回調,則忽略第二個參數。

var a = ['2', '3', '4', '5', '6', '7', '8']; 
 

 
// With two arguments: 
 
console.log(_.map(a, (num, index) => _.parseInt(num, index))); 
 
//[2, NaN, NaN, NaN, NaN, NaN, NaN] - this is the expected output 
 

 
// With all three arguments that _.map provides: 
 
console.log(_.map(a, (num, index, arr) => _.parseInt(num, index, arr))); 
 
//[2, 3, 4, 5, 6, 7, 8]
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

+0

感謝,我看到在源代碼發佈的問題,但這個專門做是爲了更在地圖工作崗位,減少等? – pranavjindal999

+0

我無法想象任何其他原因。 Thre的[jdalton的評論](https://github.com/lodash/lodash/issues/992#issuecomment-75661057)也表明了這一點。 – noppa