跳到主要内容

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

要理解这个示例,你应该具备以下 JavaScript 编程 主题的知识:

示例 1:使用 JSON.stringify() 将对象转换为字符串

// 程序将对象转换为字符串

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() 将对象转换为字符串

// 程序将对象转换为字符串

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() 函数将对象的值转换为字符串。

当使用 String() 函数对一个 Object 进行操作时,转换后的结果将给出 [object Object]。

typeof 操作符给出了 result 变量的数据类型。