1,运用toString()方法
// 把Number类型转换为String
var a = 123;
a.toString()
// console.log(typeof a) => number
// console.log(a) => 123
// 注意:toString()方法会返回一个新的值,不会改变原有值
a = a.toString(); //用变量来接受toString()方法的返回值
// console.log(typeof a) => string
// console.log(a) => 123
// 把Boolean类型转换为String
var a = true;
a = a.toString();
// console.log(typeof a) => string
// console.log(a) => true
// 把null转换为String
var a = null;
a = a.toString();
console.log(typeof a)
console.log(a)
//报错 Cannot read properties of null (reading 'toString')
// 把undefined转换为String
var a = undefined;
a = a.toString();
console.log(typeof a)
console.log(a)
//报错 Cannot read properties of null (reading 'toString')
// 注意:null和undefined没有toString()方法 不能用该方法转换,否则会报错
2,调用String()函数
// 把Number类型转换为String
var a = 123;
a = String(a);
// console.log(typeof a) => string
// console.log(a) => 123
// 把Boolean类型转换为String
var a = true;
a = String(a);
// console.log(typeof a) => string
// console.log(a) => true
// 把null转换为String
var a = null;
a = String(a);
// console.log(typeof a) => string
// console.log(a) => null
// 把undefined转换为String
var a = undefined;
a = String(a);
// console.log(typeof a) => string
// console.log(a) => undefined
总结: toString()方法和String()函数都有返回值,不改变原有值。null和undefined没有toString()方法,不可用该方法强制转换成字符串,但可用String()函数转换为字符串。
|