JavaScript 对象转字符串

在 JavaScript 中,如果想要将一个对象转换为一个字符串,常用的有以下 3 种方法。

  • 使用 JSON.stringify() 方法。
  • 使用 toString() 方法。
  • 使用 String() 函数。

使用 JSON.stringify() 方法(推荐)

在 JavaScript 中,将对象转换为字符串最常用、最推荐的,就是使用 JSON.stringify() 方法来实现。

JSON.stringify() 会将 JavaScript 对象转换成一个符合 JSON 格式的字符串。这种格式的字符串可以被网络传输,也可以被其他编程语言轻松解析。

示例 1:

const user = {
    id: 1001,
    name: "Jack",
    isAdmin: false
};

const result = JSON.stringify(user);

console.log(result);
console.log(typeof result);

运行结果如下。

{"id":1001,"name":"Jack","isAdmin":false}
string

提示: 关于 JSON.stringify() 的更详细用法,另请参阅:JavaScript JSON.stringify() 方法

使用 toString() 方法

在 JavaScript 中,所有对象都会继承 Object.prototype.toString() 方法。我们可以使用 toString() 方法来返回对象的字符串表示。

示例 2:

const user = {
    id: 1001,
    name: "Jack",
    isAdmin: false
};
const result = user.toString();

console.log(result);
console.log(typeof result);

运行结果如下。

[object Object]
string

分析:

对于普通的 JavaScript 对象来说,toString() 方法以及后面介绍的 String() 函数只会返回对象的类型描述字符串 "[object Object]",而不是对象的具体内容。

不过大多数情况下,我们更希望获取对象的内部数据情况。很显然,toString() 返回的结果是没有太多意义的。因此在实际开发中,我们并不推荐使用 String() 或 toString() 来将对象转换为字符串。

提示: 关于 toString() 方法的更详细用法,另请参阅:JavaScript 对象 toString() 方法

使用 String() 函数

在 JavaScript 中,我们可以使用 String() 函数来将任何其他类型(包括对象)转换为字符串。当 String() 用于对象时,本质上是调用 Object 对象的 toString() 方法。

示例 3:

const user = {
    id: 1001,
    name: "Jack",
    isAdmin: false
};
const result = String(user);

console.log(result);
console.log(typeof result);

运行结果如下。

[object Object]
string
给站长反馈

绿叶网正在不断完善中,小伙伴们如果发现任何问题,还望多多给站长反馈,谢谢!

邮箱:lvyenet@vip.qq.com

「绿叶网」服务号
绿叶网服务号放大
关注服务号,微信也能看教程。
绿叶网服务号