- 区别
toString()无法转换null和undefined
let a;
let b=null;
a.toString();//Uncaught TypeError: Cannot read property 'toString' of undefined
b.toString(); //Uncaught TypeError: Cannot read property 'toString' of null
String(a); //"undefined"
String(b);//"null"
- 应用
String()和toString()都是将其他类型的变量转换为字符串类型。
let a =1;
let b = 123;
String(a); // '1'
typeOf(a); // String
typeOf(b); //Number
b.toString(); // '123'
typeOf(b); //String;