Javascript does not have a full-fledged base conversion API like Java or Python, and only two apis are available. But these two apis are enough to convert up to base 36.
Number.prototype.toString()
Number overrides the toString() method on the Object prototype and can be used to convert a base 10 Number to another base.
console.log((10).toString(9));// Convert base 10 to base 9
console.log((171015).toString(16));// Switch from base 10 to base 16
console.log((33353630).toString(36));// Convert base 10 to base 36
console.log((1).toString(37));// Error at most 36 base
Copy the code
parseInt(str, radix)
A number used to convert a string to a 10 base number, where the string is a 2-36 base number.
console.log(parseInt(124123.8));
console.log(parseInt(2135142123.16));
console.log(parseInt(2135142123.36));
console.log(parseInt(2135142123.37));
console.log(parseInt(1323412.1));
console.log(parseInt(1323412, -1));
Copy the code
The radix can only be 2-36, and NaN is returned when the radix is 1 or greater than 36 or negative.
ParseInt also reads the first digit of the string, up to the first character that is not a number.
If STR is a number directly, STR is converted to number and then converted.
Conversion across base 10
console.log(parseInt(234.5).toString(36));
console.log(parseInt(234.26).toString(2));
console.log(parseInt(234.36).toString(4));
Copy the code
We can chaining parseInt and toString to do the conversion directly.
A classic interview question
let a = [1.2.3].map(parseInt)
console.log(a);
Copy the code
The first two arguments passed to map are the elements of the array and the index of the elements of the array, so 1,0 and 2,1 and 3,2. Base 0, default is base 10; There is no base 1; You can’t have a 3 in base 2.
So the result is [1, NaN, NaN].
Record the record!