JS将数字类型转为字符串类型的常见方法

1.toString() 方法

toString() 方法将数字转换为字符串

let num = 123;
let str = num.toString();
console.log(str); // "123"
console.log(typeof str); // "string"

2.String() 函数

String() 函数可以将任何类型的值转换为字符串

let num = 123;
let str = String(num);
console.log(str); // "123"
console.log(typeof str); // "string"

3.使用模板字面量

模板字面量(Template Literals)也可以用于将整数转换为字符串。 

let num = 123;
let str = `${num}`;
console.log(str); // "123"
console.log(typeof str); // "string"

4.使用加号运算符

将一个空字符串数字相加,也可以将数字转换为字符串。 

let num = 123;
let str = num + '';
console.log(str); // "123"
console.log(typeof str); // "string"

 

 

你可能感兴趣的:(javascript,前端,开发语言)