示例 1:使用 JSON.stringify() 将对象转换为字符串
// program to convert an object to a string
const person = {
name: 'Jack',
age: 27
}
const result = JSON.stringify(person);
console.log(result);
console.log(typeof result);
输出
{"name":"Jack","age":27} string
在上面的示例中,JSON.stringify()
方法用于将对象转换为字符串。
typeof
运算符会给出 result 变量的数据类型。
示例 2:使用 String() 将对象转换为字符串
// program to convert an object to a string
const person = {
name: 'Jack',
age: 27
}
const result1 = String(person);
const result2 = String(person['name']);
console.log(result1);
console.log(result2);
console.log(typeof result1);
输出
[object Object] Jack string
在上面的示例中,String()
函数将对象的值转换为字符串。
当对 Object
使用 String()
函数时,转换后的结果将是 [object Object]。
typeof
运算符会给出 result 变量的数据类型。
另请阅读