admin管理员组

文章数量:1278819

Maybe this is lame question, if so, I sincerely apologize.

I have encountered on, to me, an interesting challenge.

    <button onClick="myFunc()">Click Me</button>    

    <p id="test"></p>

    <script>
    function myFunc() {
       var n = 15               
       var a = n.toString();    // outputs 15
       var b = n.toString(2);   // outputs 1111
       var c = n.toString(9);   // outputs 16
       var d = n.toString(18);  // outputs f
       var e = n.toString(36);  // outputs f

       var total = a + "<br>" + b + "<br>" + c + "<br>" + d + "<br>" + e;

       document.getElementById('test').innerHTML=total;
    }
    </script>

I understand 2 will output binary value, and 18 & 36 will output hexadecimal value. But when I put 37 it doesn't output anything.

For example:

var f = n.toString(37);

doesn't output anything.

In the console it says: RangeError: radix must be an integer at least 2 and no greater than 36. Why?

Maybe this is lame question, if so, I sincerely apologize.

I have encountered on, to me, an interesting challenge.

    <button onClick="myFunc()">Click Me</button>    

    <p id="test"></p>

    <script>
    function myFunc() {
       var n = 15               
       var a = n.toString();    // outputs 15
       var b = n.toString(2);   // outputs 1111
       var c = n.toString(9);   // outputs 16
       var d = n.toString(18);  // outputs f
       var e = n.toString(36);  // outputs f

       var total = a + "<br>" + b + "<br>" + c + "<br>" + d + "<br>" + e;

       document.getElementById('test').innerHTML=total;
    }
    </script>

I understand 2 will output binary value, and 18 & 36 will output hexadecimal value. But when I put 37 it doesn't output anything.

For example:

var f = n.toString(37);

doesn't output anything.

In the console it says: RangeError: radix must be an integer at least 2 and no greater than 36. Why?

Share Improve this question asked May 11, 2016 at 10:19 super11super11 4768 silver badges19 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 11

https://developer.mozilla/en-US/docs/Web/JavaScript/Reference/Errors/Bad_radix

Why is it limited to 36? A radix that is larger than 10 uses alphabetical characters as digits. Therefore, the radix can not be larger than 36 as the Latin alphabet has 26 characters only.

what's more, with radix 18 you don't get hexadecimal values. hexadecimal is base 16

As the link in the other answer says, this is because with base 36 there are digits from 0 to z. For bases grater than 36, a few other non alphanumeric symbols should be added as digits.

Anyway, as you can see, base 36 is enough to invoke most of js methods

let bar = {baz(){alert(":)")}};
eval(14643.314021776406.toString(36))()

the code above will alert a smile!

It's a joke, of course :D

本文标签: javascriptWhy is toString range limited to 36Stack Overflow