JavaScript toString() vs String()

There are two ways to convert a value to a string in JavaScript

  • toString()method, except for null and undefined which do not support this method, other data types are supported , and for integers toString() also supports converting to string representations in different bases
let b = false,
    s = 'xxx',
    n = 16;

console.log("false toString():", b.toString());
console.log("'xxx' toString():", s.toString());
console.log("16 toString():", n.toString());
// 十六进制
console.log("16 toString(16):", n.toString(16));

Print

false toString(): false
'xxx' toString(): xxx
16 toString(): 16
16 toString(16): 10

  • String()Transformation function, supports all data types

Conversion rules for String():

  1. If the value to be converted has a toString() method, call it directly. The parameter of toString() cannot be specified here, so the integer is directly converted into a decimal string form, and cannot be specified as another base
  2. If null, return "null"
  3. If it is undefined, return "undefined"
let b = false,
    s = 'xxx',
    n = 16;
let x = {
    
     toString: () => 'xxx' };

console.log("String(false):", String(b));
console.log("String('xxx'):", String(s));
console.log("String(16):", String(16));
console.log("String({ toString: () => 'xxx' }):", String(x));
console.log("String(null):", String(null));
console.log("String(undefined):", String(undefined));

Print

String(false): false
String('xxx'): xxx
String(16): 16
String({ toString: () => 'xxx' }): xxx
String(null): null
String(undefined): undefined

Guess you like

Origin blog.csdn.net/jiang_huixin/article/details/125933863