What does it mean when there is a number parameter passed to toString?

后端 未结 3 1663
耶瑟儿~
耶瑟儿~ 2020-12-25 12:10

I\'m just wondering what it means to attach a number as a parameter to the toString() method

E.g. obj.toString(10);

I googled a

相关标签:
3条回答
  • 2020-12-25 12:41

    This only works on Number objects and is intended to give you a way of displaying a number with a certain radix:

    var n = 256;
    var d = n.toString(10); // decimal: "256"
    var o = n.toString(8);  // octal:   "400"
    var h = n.toString(16); // hex:     "100"
    var b = n.toString(2);  // binary:  "100000000"
    var w = n.toString(20); // base 20: "cg"
    

    Note that the radix must be an integer between 2 and 36 or toString() will raise an error.

    0 讨论(0)
  • 2020-12-25 12:43

    The additional parameter works only for Number.prototype.toString to specify the radix (integer between 2 and 36 specifying the base to use for representing numeric values):

    var number = 12345;
    number.toString(2) === "11000000111001"
    number.toString(3) === "121221020"
    // …
    number.toString(36) === "9ix"
    
    0 讨论(0)
  • 2020-12-25 12:55

    It's not defined as a globally-applicable argument to toString, it only makes sense on Number, where it specifies the base to write in. You can use eg. n.toString(16) to convert to hex.

    The other built-in objects don't use any arguments and JavaScript will silently ignore unused arguments, so passing 16 to any other toString method will make no difference. You can of course make your own toString methods where optional arguments can mean anything you like.

    0 讨论(0)
提交回复
热议问题