[‘1′,’2′,’3’]. Map (parseInt)

Your first reaction is not [1,2,3], but the real result is [1, NaN, NaN]. Why is that? First take a look at the map method in the array.

The map method

To introduce the MDN interpretation, the map() method creates a new array, the result of which is the result returned when each element in the array calls a provided function.

var arr = [1, 2, 3]; var arr1 = arr.map(x => x+1); console.log(arr1); / / 2 and 4Copy the code

You can see that the map method accepts a function that iterates over each element in the array.

new_array = [].map(function callback(currentValue[,index[,array]]){ // Return element for new_array }[, thisArg]);
Copy the code

This callback can take three arguments, the first representing the element being processed and the second representing the index of that element.

ParseInt function

ParseInt is used to parse a string into an integer with a specified cardinality.

parseInt(string, radix)
Copy the code

Accepts two arguments, the first representing the value being processed (string) and the second representing the cardinality at parsing time. Radix is an integer between 2 and 36 and returns the parsed integer value. NaN is returned if the first character of the parsed parameter cannot be converted to a numeric type

praseInt('111') // 111
parseInt('111'| | | | | | | | | | | | | | | | | | | | | | |'111', 1) // NaN 【2 <= radix <= 36】'111'/ / 7, 2)Copy the code

From the above we can see that different values are returned depending on the specific radix.

The radix argument of n treats the first argument as an n-base representation of a number and returns a decimal value.

parseInt('123'/ / will, 5)'123'As a base 5 number, return the decimal number 38 => 1*5^2 + 2*5^1 + 3*5^0 = 38Copy the code

[‘1’, ‘2’, ‘3’]. Map (parseInt);

  1. parseInt(‘1’, 0); // When radix is 0, use the default base 10.
  2. parseInt(‘2’, 1); // The radix value is 2-36, and NaN is not resolved
  3. parseInt(‘3’, 2); // If the value of a base 2 number is less than 3 and cannot be resolved, NaN is returned

The map function returns an array, so the result is [1, NaN, NaN]