Array.prototype.toString()

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2015 年 7 月⁩以來,各瀏覽器均已提供此特性。

toString() 方法 Array 例項返回一個字串,表示指定的陣列及其元素。

試一試

const array = [1, 2, "a", "1a"];

console.log(array.toString());
// Expected output: "1,2,a,1a"

語法

js
toString()

引數

無。

返回值

表示陣列元素的字串。

描述

Array 物件覆蓋了 ObjecttoString 方法。陣列的 toString 方法內部呼叫 join(),該方法將陣列連線起來,並返回一個包含由逗號分隔的每個陣列元素的字串。如果 join 方法不可用或不是函式,則改用 Object.prototype.toString,返回 [object Array]

js
const arr = [];
arr.join = 1; // re-assign `join` with a non-function
console.log(arr.toString()); // [object Array]

console.log(Array.prototype.toString.call({ join: () => 1 })); // 1

當陣列需要表示為文字值或在字串連線中引用陣列時,JavaScript 會自動呼叫 toString 方法。

Array.prototype.toString 會遞迴地將每個元素(包括其他陣列)轉換為字串。由於 Array.prototype.toString 返回的字串沒有分隔符,巢狀陣列看起來像是被展平了。

js
const matrix = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9],
];

console.log(matrix.toString()); // 1,2,3,4,5,6,7,8,9

當陣列是迴圈引用(它包含一個自身作為元素的元素)時,瀏覽器會透過忽略迴圈引用來避免無限遞迴。

js
const arr = [];
arr.push(1, [3, arr, 4], 2);
console.log(arr.toString()); // 1,3,,4,2

示例

使用 toString()

js
const array = [1, 2, "a", "1a"];

console.log(array.toString()); // "1,2,a,1a"

對稀疏陣列使用 toString()

遵循 join() 的行為,toString() 將空槽視為 undefined 併產生額外的分隔符。

js
console.log([1, , 3].toString()); // '1,,3'

對非陣列物件呼叫 toString()

toString()通用的。它期望 this 具有 join() 方法;否則,它將使用 Object.prototype.toString()

js
console.log(Array.prototype.toString.call({ join: () => 1 }));
// 1; a number
console.log(Array.prototype.toString.call({ join: () => undefined }));
// undefined
console.log(Array.prototype.toString.call({ join: "not function" }));
// "[object Object]"

規範

規範
ECMAScript® 2026 語言規範
# sec-array.prototype.tostring

瀏覽器相容性

另見