“This is the 12th day of my participation in the Gwen Challenge in November. See details of the event: The Last Gwen Challenge 2021”.
preface
In our projects, we will often encounter data that needs to be converted from String to Number, where we usually use parseInt() or Number() or syntax sugar plus: +’1324′
ParseInt (map) parseInt (map) parseInt
parseInt
The grammar of the parseInt
parseInt(string, radix)
Copy the code
- The string argument is a string or is converted to a string if it is not a string.
- Radix is an integer between 2 and 36 that represents the radix of the string, and when radix is not specified or radix is 0, different incoming values yield different results
- If a string begins with “0x”, the string is recognized as a hexadecimal integer
- If a string begins with a 0, characters are recognized as octal or hexadecimal numbers
- If a string begins with a number from 1 to 9, it will be recognized as a decimal integer
- Portal: What happens when the Radix parameters are not transmitted
- NaN is returned if the first character of the parsed parameter cannot be converted to a numeric type
Portal: explanation of parseInt on MDN
Look at some chestnuts:
ParseInt ("1",0) // Converts to base 10, returns 1 parseInt("2",1) // Converts to base binary, returns NaN parseInt("3",2) // Converts to base binary, because the first argument is "3", non-binary, then the first argument is invalid, Return NaN parseInt("11",2) // Convert to base binary, the first argument is a valid binary, and return 3Copy the code
map
The map of grammar
Portal: Map explanation on MDN
Map calls the defined callback function on each element of the array and returns the array containing the results
array.map(callback(currentValue, index, arr), thisValue)
Copy the code
- Callback: Mandatory function. Each element in the array executes this function
- CurrentValue will choose. The value of the current element.
- Index: Optional. The index value of the current element
- Arr: Optional. The current element belongs to the array object
- ThisValue: Optional. Object is used when the callback is executed, passed to the function, and used as the value of “this”. If thisValue is omitted, the value of “this” is “undefined”
When parseIn encounters Map
["1", "2", "3"].map(parseInt)
Copy the code
Guess what it prints?
Answer: [1, NaN, NaN]Copy the code
This result is due to the map callback function. The map callback function takes three parameters by default
Back to the question above:
["1", "2", "3"].map(parseInt) // Callback equals parseInt(1, 0, [1,2,3]); ParseInt (2, 1, 1, 2, 3); ParseInt (3, 2, 1, 2, 3);Copy the code
Given the use of parseInt above, it is easy to see why [1, NaN, NaN] is printed