String()和toString()都是将其他类型(数值、字符串、对象、布尔)的变量转换为字符串类型。
区别:
toString()方法: 常用,只是toString()无法转换null和undefined
String() 属于强制转换,可以转任何类型 ,null转换的结果为null;undefined转换的结果为undefined;
示例:
let a = 1; let b = 123;
console.log(String(a)); // '1'
console.log(typeof String(a)); // string
console.log(typeof(b)); //number
console.log(b.toString()); // '123'
console.log(typeof b.toString()); //string;
let a;//默认初始值为undefined
let b=null;
console.log(a.toString());//Uncaught TypeError: Cannot read property 'toString' of undefined
console.log(b.toString()); //Uncaught TypeError: Cannot read property 'toString' of null
console.log(String(a)); //"undefined"
console.log(String(b));//"null"
但愿人长久,顿顿不长肉。