问题
I'm taking a course on JavaScript but have no guide on toString
method, what's the purpose of these two outputs in JavaScript:
(35).toString(36)
>>>"z"
!!!(35).toString(37)
>>> throws aRangeError
!!!
I am utterly confused as to why I am getting these results, I would really appreciate it if someone could shed some light on this.
回答1:
tldr: Number.prototype.toString
can take an argument called radix
that specifies the numeric base to use for the string representation of the number in question.
Object.prototype.toString()
An object's toString
method is supposed to return a string representation of that object (I say "supposed" because you can modify it so it doesn't return a string). 35
is clearly not an object, it is a primitive, but you are using it like an object, which causes JavaScript to create a temporary Number
object for that toString
call (see this StackOverflow answer on autoboxing).
Number.prototype.toString()
About the confusing behavior you are getting by passing 36
to (35).toString
: it is because Number.prototype.toString can take an argument that you can use to specify the numeric base to use for the string representation of that number, the argument must be an integer (or any other value that can be coerced to an integer, e.g 35..toString([20])
) between 2
and 36
, so 2 <= [radix] <= 36
(this means your second example will throw a RangeError).
So, when you execute (35).toString(36)
, 2 things happen (not necessarily in my order, and most likely it is done in a single step, 35 ====> [string representation of 35 in numeric format specified by "radix"]
):
- Generate a string representation of the number
35
. - Convert the string generated in step #1 to the number base specified by
radix
.
For example, if you wanted a string representation of 35
, in binary form:
console.log(35..toString(2)); // "100011"
Fun fact: the syntax [integer]..[method]
is totally valid in JavaScript, the first .
is interpreted as a decimal point, the latter as the .
that precedes the name of an object's method/property.
Radix
If you don't know what a "radix" is (because I didn't prior to this question, and no, I am no caveman, English is not my native language), here is the definition I got by a Google search for "radix meaning":
the base of a system of numeration.
回答2:
toString converts an Int to a string. An int is used for math and a string is used as text and math should not be done on it.
Maybe a little more of the code you are looking at would shed more light on what is going on in the script
来源:https://stackoverflow.com/questions/46701301/what-does-passing-an-integer-number-as-the-argument-for-tostring-do