Detailed explanation of JavaScript's toString() method

1. Introduction

In JavaScript, toString()methods are built-in methods of many data types, which are used to convert specific data types into strings. However, the functions in different data types are not exactly the same. Let’s explain in detail toString()the use and function of methods in various data types.

2. Details

1、Object

Object​Type toString()method is used to return a string representing the object. This string does not turn all key-value pairs of the object into strings, but generates a primitive value and returns it "[object Type]", Typerepresenting the type of the object and its attribute values. Depending on whether the calling object has Symbol.toStringTaga property whose value is a string, its value will be used as Typethe value of .

​ All objects that inherit from Object.prototype(that is, objects other than null-prototype objectstoString() ) inherit methods.

In addition, we can also rewrite methods through the prototype chain Object.prototype.toString()to achieve specific functions.

    let o = new Object();
    let o2 = {
    
    
      a: 1,
      b: 2
    };
    console.log(o.toString()); // 输出:[object Object]
    console.log(o2.toString()); // 输出:[object Object]
    // 重写toString方法
    Object.prototype.toString = function () {
    
    
      // this指向调用该方法的对象
      // 返回对象的JSON字符串
      return JSON.stringify(this);
    }
    // 调用重写后的toString方法
    console.log(o.toString()); // 输出:{}
    console.log(o2.toString()); // 输出:{"a":1,"b":2}
2、String

​Inherited andString overridden method to return the string itself (if it is a primitive value) or the string encapsulated by the object. Its implementation is identical to .ObjecttoString()StringString.prototype.valueOf()

When an object is used in a context that expects a string, such as a template string String, its methods will be called implicitly toStringto turn it into a string, and the literal toStringmethod will not be called.

Similarly, we can also rewrite methods through the prototype chain String.prototype.toString()to achieve specific functions.

Case code:
    // 利用构造函数传建一个字符串
    let s = new String('hello');
    // 通过字面量创建一个字符串
    let s2 = 'hello2';
    // 调用默认的toString方法
    console.log(s.toString()); // 输出:hello
    console.log(s2.toString()); // 输出:hello2
    // 重写toString方法
    String.prototype.toString = function () {
    
    
      // this指向调用该方法的对象字符串
      // 返回对象字符串的长度
      return this.length;
    }
    // 调用重写后的toString方法
    console.log(s.toString()); // 输出:5
    console.log(s2.toString()); // 输出:6
    // 在模板字符串等期望字符串的上下文中使用String对象时,会自动调用toString方法
    console.log(`你好 ${
      
      s}`); // 输出:你好 5
    console.log(`你好 ${
      
      new String('zzq')}`); // 输出:你好 3
    // 字面量就不会自动调用toString方法
    console.log(`你好 ${
      
      s2}`); // 输出:你好 hello2		
3、Number

The typeNumber inherits and overrides the Objectmethod toString()so that toString([radix])the method returns a string representing the numeric value. The optional parameter radixrepresents the base of the numeric value, which is the base of the number. The parameter range is [2,36], and the default base is 10, which is decimal.

For base numbers above 10, lowercase letters are used to represent numbers greater than 9. For example, for hexadecimal numbers (base 16), ato fis used to represent numbers greater than 9. If the number to be converted Numberis negative, the negative sign is retained as the first character of the string. But-0 the exception will become after conversion to string 0. InfinityReturn "Infinity", and NaNreturn "NaN".

When an object is used in a context that expects a string, such as a template string String, its methods will be called implicitly toStringto turn it into a string, and the literal toStringmethod will not be called.

Similarly, we can also rewrite methods through the prototype chain Number.prototype.toString()to achieve specific functions.

We can also use parseInt()the and toString()method to convert a non-decimal numeric string into a base-specific string. If the original number string is too large (e.g. greater than Number.MAX_SAFE_INTEGER), then should be used BigIntinstead. However, BigIntthe constructor only supports strings representing numeric literals (i.e. strings starting with 0b, 0oor ).0x

Case code:
    // 利用构造函数传建一个数字
    let n = new Number(123);
    // 通过字面量创建一个数字
    let n2 = 321;
    // 调用默认的toString方法
    console.log(n.toString()); // 输出:123
    console.log(n2.toString()); // 输出:321
    // 传入参数2,表示转换为二进制
    console.log(n.toString(2)); // 输出:1111011
    // 传入参数16,表示转换为十六进制
    console.log(n.toString(16)); // 输出:7b
    // 负数转换为二进制
    console.log((-n).toString(2)); // 输出:-1111011
    // 负数转换为十六进制
    console.log((-n).toString(16)); // 输出:-7b
    // -0是个例外 转换为字符串后,会变成0
    n = -0;
    console.log(n.toString()); // 输出:0
    // parseInt和toString方法 结合使用,可以实现进制转换
    // 十六进制转换为二进制
    n = '7ba1';
    console.log(parseInt(n, 16).toString(2)); // 输出:11110111010001
    // 重写toString方法
    Number.prototype.toString = function () {
    
    
      // this指向调用该方法的对象数字
      // 返回对象数字的平方
      return this * this;
    }
    n = 2;
    // 调用重写后的toString方法
    console.log(n.toString()); // 输出:4
    // 在模板字符串等期望字符串的上下文中使用Number对象时,会自动调用toString方法
    console.log(`你好 ${
      
      n}`); // 输出:你好 4
    console.log(`你好 ${
      
      new Number(3)}`); // 输出:你好 9
    // 字面量就不会自动调用toString方法
    console.log(`你好 ${
      
      n2}`); // 输出:你好 321
4、Array

Array​Type toString()method is used to return a ,string concatenated by all elements of the array. This method actually calls Array.join(',')the method internally.

​ If the array join()method is overridden, toString()the method will also be affected. If join()the method is unavailable or overridden as a non-function attribute, the method will be called according to the prototype Objectchain toString().

Similarly, we can also rewrite methods through the prototype chain Array.prototype.toString()to achieve specific functions.

Case code:
    let arr1 = [1, 2, 3];
    let arr2 = new Array(1, 2, 3);
    console.log(arr1.toString()); // 输出:1,2,3
    console.log(arr2.toString()); // 输出:1,2,3
    // 改写join()方法为另外的函数
    arr1.join = function () {
    
    
      // this指向调用该方法的数组
      // 返回数组的JSON字符串
      return JSON.stringify(this);
    }
    // 调用重写后的join方法
    console.log(arr1.join()); // 输出:[1,2,3]
    // 调用toString方法 其内部隐式调用了join方法
    console.log(arr1.toString()); // 输出:[1,2,3]
    // 改写join()方法为非函数
    arr2.join = 1;
    // 调用重写后的join方法
    console.log(arr2.join); // 输出:1
    // 调用toString方法 其内部隐式调用了join方法
    // 由于join不是函数,所以会按原型链调用Object的toString方法
    console.log(arr2.toString()); // 输出:[object Array]
		// 重写toString方法
    Array.prototype.toString = function () {
    
    
      // this指向调用该方法的数组
      // 返回数组的JSON字符串
      return JSON.stringify(this);
    }
    // 调用重写后的toString方法
    console.log(arr1.toString()); // 输出:[1,2,3]
    console.log(arr2.toString()); // 输出:[1,2,3]

5、Date

Date​Type toString()method is used to return a string representing the date and time in the local time zone. Its format is equivalent to concatenating the return values ​​​​of toDateString()the and toTimeString()methods with a space, but overriding these two methods will not affect toString()the method. Because these two methods are not called inside the method.

​ When Datedata of the type is converted to a string, for example: string concatenation ( 'string'+date), the method is automatically called toString().

​ If you just want to get the date, it is recommended to use toDateString(). It is recommended to use if you just want to get the time toTimeString(). It is recommended to use if you want to get UTC time toUTCString(). Recommended if you want to get a readable time format toLocaleString().

Similarly, we can also rewrite methods through the prototype chain Date.prototype.toString()to achieve specific functions.

Case code:
    let date1 = new Date();
    // 调用默认的toString方法
    console.log(date1.toString()); // 输出:Fri Jan 05 2024 15:03:30 GMT+0800 (中国标准时间)
    // 调用toDateString()和toTimeString()方法
    console.log(date1.toDateString() + ' ' + date1.toTimeString()); // 输出:Fri Jan 05 2024 15:03:30 GMT+0800 (中国标准时间)
    // 重写toDateString()方法
    Date.prototype.toDateString = function () {
    
    
      // this指向调用该方法的日期对象
      return JSON.stringify(this.getFullYear());
    }
    // 调用重写后的toDateString方法
    console.log(date1.toDateString()); // 输出:2024
    // 调用toString方法 并不会收到影响
    console.log(date1.toString()); // 输出:Fri Jan 05 2024 15:03:30 GMT+0800 (中国标准时间)
    // 获取UTC时间
    console.log(date1.toUTCString()); // 输出:Fri, 05 Jan 2024 07:03:30 GMT
    // 获取本地时间的字符串
    console.log(date1.toLocaleString()); // 输出:2024/1/5 15:04:24
    // 改写toString方法
    Date.prototype.toString = function () {
    
    
      // this指向调用该方法的日期对象
      // 返回日期对象的年份
      return this.getFullYear();
    }
    // 调用重写后的toString方法
    console.log(date1.toString()); // 输出:2024
6、Function

Function​Type toString()method is used to return a string representing the source code of the function. Starting from ES2018, the specification requires toString()that the return value is exactly the same as the declared source code, including spaces and comments. The output formats of ordinary functions, anonymous functions, and arrow functions are slightly different.

​ When Functiondata of the type is converted to a string, for example: string concatenation ( 'string'+ function), the method is automatically called toString().

Similarly, we can also rewrite methods through the prototype chain Date.prototype.toString()to achieve specific functions.

Case code:
    let f = function (a, b) {
    
    
      // 返回a+b的值
      return a + b;
    }
    // 利用构造函数传建一个函数 注意a跟+之间没有空格
    let f2 = new Function('a', 'b', 'return a+ b;');
    let f3 = (a, b) => {
    
    
      return a + b;
    }
    // 调用默认的toString方法
    console.log(f.toString()); // 输出:function (a, b) { // 返回a+b的值 return a + b; }
    console.log(f2.toString()); // 输出:function anonymous(a, b) { return a+ b; }
    console.log(f3.toString()); // 输出:(a, b) => { return a + b; }
    // 重写toString方法
    Function.prototype.toString = function () {
    
    
      // this指向调用该方法的函数
      // 返回函数的参数个数
      return this.length;
    }
    // 调用重写后的toString方法
    console.log(f.toString()); // 输出:2
    console.log(f2.toString()); // 输出:2
    console.log(f3.toString()); // 输出:2
7、Boolean

BooleanMethod of type toString(), used to return the string form of the current Boolean value.

Similarly, we can also rewrite methods through the prototype chain Boolean.prototype.toString()to achieve specific functions.

Case code:
    let a = true;
    let b = false;
    // 调用默认的toString方法
    console.log(a.toString()); // 输出:true
    console.log(b.toString()); // 输出:false
    // 与布尔值进行对比
    console.log(a.toString() == true); // 输出:false
    console.log(a.toString() === true); // 输出:false
    console.log(b.toString() == false); // 输出:false
    console.log(b.toString() === false); // 输出:false
8、Symbol

Symbol​Type toString()method used to return the string form of the current Symbol. SymbolData cannot be implicitly converted to a string, so toString()methods are needed to convert the data to a string.

Similarly, we can also rewrite methods through the prototype chain Boolean.prototype.toString()to achieve specific functions.

​ For more related content, please view: JavaScript's Symbol data type .

Case code:
  // 创建一个symbol
    const a = Symbol("aaa");
    console.log(a.toString()); // Symbol(aaa)
    // 创建一个全局symbol
    const b = Symbol.for("bbb");
    console.log(b.toString()); // Symbol(bbb)
    // 重写toString方法
    Symbol.prototype.toString = function () {
    
    
      // this指向调用该方法的symbol
      // 返回symbol的描述
      return this.description;
    }
    // 调用重写后的toString方法
    console.log(a.toString()); // 输出:aaa
    console.log(b.toString()); // 输出:bbb
9、Selection

Selection​Type toString()method used to return a Selectionstring representing the current object.

​ When Selectiondata of the type is converted to a string, for example: string concatenation ( 'string'+ Selection), the method is automatically called toString().

​For more related content, see: Selection object and Range object .

10. null and undefined

null​ and undefinedare special values ​​in JavaScript, they have no toString()methods. Calling a method that does not exist will result in TypeErroran error. If you want to convert them to strings, you can use other methods such as using conditional statements or template strings to process them.

11. Others

HTMLHyperlinkElementUtils.toString()

URLSearchParams.toString()

Guess you like

Origin blog.csdn.net/weixin_45092437/article/details/135412772