2017-07-19 3 views
1

Ich las ein Blog, das besagt, dass _.parseInt sicher ist. Gemäß der Dokumentation akzeptiert es auch das Radix als zweites Argument wie das native parseInt. Im Allgemeinen kann beim Zuordnen eines Arrays ein unerwartetes Verhalten auftreten, wenn parseInt direkt an map übergeben wird.Wie analysiert lodashs _.parseInt sicher auf Karte

Wie funktioniert lodashs parseInt sicher?

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? 

Wie unterscheidet sich Fall 2 auch von Fall 3?

Antwort

1

The implementation von _.parseInt dauert ein "Geheimnis" dritte Argument.

Wenn dieses dritte Argument wie in einem _.map(a, _.parseInt) Callback bereitgestellt wird, wird das zweite Argument ignoriert.

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

Dank, sah ich, dass im Quellcode nach der Frage der Veröffentlichung aber wurde diese speziell getan, um es für Karte funktioniert, reduziert, etc? – pranavjindal999

+0

Ich kann mir keinen anderen Grund dafür vorstellen. Thre's [dieser Kommentar von jdalton] (https://github.com/lodash/lodash/issues/992#issuecomment-75661057) zeigt dies ebenfalls an. – noppa