ZetCode

JavaScript toString 方法

最后修改于 2025 年 4 月 4 日

在本文中,我们将展示如何使用 JavaScript 中的 toString 方法将对象转换为字符串。

toString 方法

toString 方法返回一个表示该对象的字符串。每个 JavaScript 对象都从 Object 原型继承此方法。不同的类型会重写此方法,以返回有意义的字符串表示形式。

原始值(如数字和布尔值)有它们自己的 toString 实现。数组返回用逗号分隔的元素,而日期返回人类可读的日期字符串。默认情况下,对象返回 [object Object]

当需要将对象表示为文本值时,会自动调用此方法。这发生在字符串连接期间或使用 alert() 时。您也可以在需要时显式调用它。

基本 toString 示例

以下示例演示了 toString 方法与数字的基本用法。

main.js
const num = 42;
const str = num.toString();

console.log(typeof num);  // number
console.log(typeof str);  // string
console.log(str);         // "42"

我们将一个数字转换为其字符串表示形式。原始数字保持不变。toString 方法返回一个新的字符串值。请注意,由于自动装箱,我们可以在原始值上调用 toString。

$ node main.js
number
string
42

数组 toString

数组有它们自己的 toString 实现,它连接元素。

main.js
const fruits = ['apple', 'banana', 'cherry'];
const str = fruits.toString();

console.log(str);
console.log(typeof str);

数组的 toString 方法使用逗号连接所有元素。嵌套数组也会被展平和转换为字符串。这等同于调用不带参数的 join 方法。

$ node main.js
apple,banana,cherry
string

对象 toString

普通对象从 Object.prototype 继承默认的 toString 方法。

main.js
const person = {
  name: 'John Doe',
  age: 30,
  occupation: 'Developer'
};

console.log(person.toString());

默认的对象 toString 方法返回 [object Object]。为了获得更有用的输出,我们通常会重写此方法或使用 JSON.stringify。该格式显示了对象的类型,但没有显示其内容。

$ node main.js
[object Object]

自定义 toString

我们可以重写 toString 来提供有意义的字符串表示形式。

main.js
function Person(name, age) {
  this.name = name;
  this.age = age;
}

Person.prototype.toString = function() {
  return `${this.name} (${this.age})`;
};

const person = new Person('Alice', 25);
console.log(person.toString());
console.log(`Person: ${person}`);  // implicit call

我们为 Person 构造函数创建一个自定义的 toString 方法。当对象用于字符串上下文中时,会自动调用此方法。这提供了对对象如何表示为字符串的控制。

$ node main.js
Alice (25)
Person: Alice (25)

数字基数转换

数字的 toString 可以转换为不同的数字系统。

main.js
const num = 255;

console.log(num.toString());    // "255" (default base 10)
console.log(num.toString(2));  // "11111111" (binary)
console.log(num.toString(8));  // "377" (octal)
console.log(num.toString(16)); // "ff" (hexadecimal)

数字的 toString 接受一个基数参数(2-36)。这允许转换为不同的进制。常见的进制包括 2(二进制)、8(八进制)、10(十进制)和 16(十六进制)。输出始终是一个字符串。

$ node main.js
255
11111111
377
ff

来源

对象 toString - 语言参考

在本文中,我们演示了如何使用 toString() 方法将 JavaScript 中的对象转换为字符串。

作者

我的名字是 Jan Bodnar,我是一位充满激情的程序员,拥有丰富的编程经验。自 2007 年以来,我一直在撰写编程文章。迄今为止,我撰写了 1,400 多篇文章和 8 本电子书。我拥有超过十年的编程教学经验。

列出 所有 JS 数组函数。