What does passing an integer number as the argument for `toString` do?

风流意气都作罢 提交于 2019-12-02 13:20:56
doubleOrt

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"]):

  1. Generate a string representation of the number 35.
  2. 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.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!