Array.prototype.toString()

基线 广泛可用

此功能已得到良好建立,并在许多设备和浏览器版本中运行。它自 2015 年 7 月.

报告反馈

试一试

语法

The toString() method of Array instances returns a string representing the specified array and its elements.
toString()

js

参数

无。

返回值

描述

一个表示数组元素的字符串。

The toString() method of Array instances returns a string representing the specified array and its elements.
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

The Array object overrides the toString method of Object. The toString method of arrays calls join() internally, which joins the array and returns one string containing each array element separated by commas. If the join method is unavailable or is not a function, Object.prototype.toString is used instead, returning [object Array].

当数组要以文本值表示或数组在字符串连接中被引用时,JavaScript 会自动调用 toString 方法。

The toString() method of Array instances returns a string representing the specified array and its elements.
const matrix = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9],
];

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

Array.prototype.toString 递归地将每个元素(包括其他数组)转换为字符串。由于 Array.prototype.toString 返回的字符串没有分隔符,因此嵌套数组看起来像是扁平化的。

The toString() method of Array instances returns a string representing the specified array and its elements.
const arr = [];
arr.push(1, [3, arr, 4], 2);
console.log(arr.toString()); // 1,3,,4,2

示例

当数组是循环的(它包含一个元素,该元素本身是数组)时,浏览器会通过忽略循环引用来避免无限递归。

The toString() method of Array instances returns a string representing the specified array and its elements.
const array1 = [1, 2, "a", "1a"];

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

使用 toString()

对稀疏数组使用 toString()

The toString() method of Array instances returns a string representing the specified array and its elements.
console.log([1, , 3].toString()); // '1,,3'

遵循 join() 的行为,toString() 将空槽位与 undefined 相同对待,并产生一个额外的分隔符

对非数组对象调用 toString()

The toString() method of Array instances returns a string representing the specified array and its elements.
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]"

规范

toString()泛型 的。它期望 this 具有 join() 方法;或者,如果没有,则使用 Object.prototype.toString() 代替。
规范
# ECMAScript 语言规范

浏览器兼容性

sec-array.prototype.tostring

另请参阅