JS中可以使用以下几种方法把其它类型转成字符串:
-
toString() 方法:可以把数字、布尔值和对象转成字符串。但是对于 null 和 undefined,不能直接使用 toString() 方法,因为会抛出错误。
-
String() 函数:可以把数字、布尔值、对象、null 和 undefined 转成字符串。注意,使用该函数将 null 和 undefined 转换成字符串时,会得到 "null" 和 "undefined" 字符串。
-
模板字符串:可以把变量或表达式嵌入到字符串中。使用 反引号 (``) 把字符串包起来,并在变量或表达式之间使用 ${} 来插入它们。
转成字符串时的规则:
-
对于对象,会调用其 toString() 方法,如果没有定义该方法,则会返回 "[object Object]" 字符串。
-
对于数字,直接转成相应的字符串。
-
对于布尔值,true 转成 "true" 字符串,false 转成 "false" 字符串。
-
对于 null 和 undefined,使用 String() 函数将其转换成 "null" 和 "undefined" 字符串。
例如:
let num = 123;
let bool = false;
let obj = { a: 1, b: 2 };
let nullVar = null;
let undefinedVar;
console.log(num.toString()); // "123"
console.log(String(bool)); // "false"
console.log(obj.toString()); // "[object Object]"
console.log(String(nullVar)); // "null"
console.log(String(undefinedVar)); // "undefined"
// Using template literals to convert variables to strings
console.log(`My number is ${num}`); // "My number is 123"
console.log(`The value of obj is ${obj}`); // "The value of obj is [object Object]"