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
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.
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"
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.