このページはコミュニティーの尽力で英語から翻訳されました。MDN Web Docsコミュニティーについてもっと知り、仲間になるにはこちらから。
Array.prototype.toString()
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since 2015年7月.
toString() はArray インスタンスのメソッドで、指定された配列とその要素を表す文字列を返します。
In this article
試してみましょう
const array = [1, 2, "a", "1a"];console.log(array.toString());// 予想される結果: "1,2,a,1a"構文
toString()引数
なし。
返値
配列の要素の文字列表現です。
解説
Array オブジェクトはObject のtoString メソッドをオーバーライドしています。配列のtoString メソッドは内部的にjoin() を呼び出します。そちらで配列を結合し、配列のすべての要素をカンマで区切って一つの文字列に収めて返します。join メソッドが利用できないか関数ではなかった場合、代わりにObject.prototype.toString が使用され、[object Array] を返します。
const arr = [];arr.join = 1; // `join` を関数ではないものに再代入console.log(arr.toString()); // [object Array] と出力console.log(Array.prototype.toString.call({ join: () => 1 })); // 1 と出力配列を文字列値として表す必要がある場合や、配列が文字列の結合として参照されるとき、 JavaScript はtoString メソッドを自動的に呼び出します。
Array.prototype.toString は他の配列も含めて、再帰的にそれぞれの要素を文字列に変換します。Array.prototype.toString` が返す文字列には区切り文字がないので、入れ子配列は平坦化されたように見えます。
const matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9],];console.log(matrix.toString()); // 1,2,3,4,5,6,7,8,9配列が循環している(コンテナーそのものである要素を格納している)場合、ブラウザーは循環参照を無視することで無限の再帰を避けます。
const arr = [];arr.push(1, [3, arr, 4], 2);console.log(arr.toString()); // 1,3,,4,2例
>toString() の使用
const array = [1, 2, "a", "1a"];console.log(array.toString()); // "1,2,a,1a"疎配列における toString() の使用
join() の動作に従い、toString() は空のスロットをundefined と同じように扱い、余分な区切り文字を生成します:
console.log([1, , 3].toString()); // '1,,3'配列以外のオブジェクトに対する toString() の呼び出し
toString() は汎用的です。このメソッドはthis がjoin() メソッドを持っていることを期待します。ない場合は、代わりにObject.prototype.toString() を使用します。
console.log(Array.prototype.toString.call({ join: () => 1 }));// 1; a numberconsole.log(Array.prototype.toString.call({ join: () => undefined }));// undefinedconsole.log(Array.prototype.toString.call({ join: "not function" }));// "[object Object]"仕様書
| Specification |
|---|
| ECMAScript® 2026 Language Specification> # sec-array.prototype.tostring> |