JavaScript 程序:将对象转换为字符串

要理解此示例,您应了解以下 JavaScript 编程 主题


示例 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 变量的数据类型。


另请阅读

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战