[Front-end interview questions] ['1', '2', '3'].map(parseInt) what & why ?

When I first saw this question, the answer that popped up in my mind was [1, 2, 3] , but the real answer is [1,

NaN, NaN]


First let's review the first parameter of the map function, callback . This callback can be

Receives three parameters, where the first parameter represents the currently processed element, while the second parameter represents the

The index of the element.

arr.map(callback: (value: T, index: number, array: T[]) => U, thisArg?: any);

And parseInt is used to parse the string, making the string an integer of the specified base. receive two

Parameters, the first represents the value (string) to be processed, and the second represents the base when parsing.

parseInt(string, radix)

After understanding these two functions, we can simulate the operation:

Pass each element of the array to the specified function for processing, and return the processed array, so ['1', '2', '3'].map(parseInt) is to use strings 1, 2, 3 as elements ; 0, 1, 2 are used as subscripts to call the parseInt function respectively. That is, the results of parseInt('1',0), parseInt('2',1), and parseInt('3',2) are obtained respectively.

parseInt( '1' , 0 ) //When the radix is ​​0, and the string parameter does not start with "0x" and "0", it will be processed according to base 10. Return 1 at this time;

parseInt( '2' , 1 ) //Among the numbers represented by base 1 (1 base), the maximum value is less than 2, so it cannot be parsed and NaN is returned;

parseInt( '3' , 2 ) //Among the numbers represented by base 2 (binary), the maximum value is less than 3, so it cannot be parsed and NaN is returned;

Guess you like

Origin blog.csdn.net/qq_38679823/article/details/127899007