pFad - Phone/Frame/Anonymizer/Declutterfier! Saves Data!


--- a PPN by Garber Painting Akron. With Image Size Reduction included!

URL: http://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/toString

7c-4bdf-a490-390a1aebf6dd/airgap.js" >

此页面由社区从英文翻译而来。了解更多并加入 MDN Web Docs 社区。

View in English Always switch to English

Array.prototype.toString()

基线 广泛可用

自 2015年7月 起,此特性已在主流浏览器中得到支持,可在大多数设备和浏览器版本中正常使用。

toString() 方法返回一个字符串,表示指定的数组及其元素。

尝试一下

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

console.log(array1.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; // 将 `join` 重新赋值为非函数的值
console.log(arr.toString()); // [object Array]

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

当数组需要被表示为文本值,或者当数组在字符串拼接中被引用时,JavaScript 会自动调用 toString() 方法。

示例

使用 toString()

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

console.log(array1.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; 一个数字
console.log(Array.prototype.toString.call({ join: () => undefined }));
// undefined
console.log(Array.prototype.toString.call({ join: "not function" }));
// "[object Object]"

规范

规范
ECMAScript® 2027 Language Specification
# sec-array.prototype.tostring

浏览器兼容性

参见

pFad - Phonifier reborn

Pfad - The Proxy pFad © 2024 Your Company Name. All rights reserved.





Check this box to remove all script contents from the fetched content.



Check this box to remove all images from the fetched content.


Check this box to remove all CSS styles from the fetched content.


Check this box to keep images inefficiently compressed and original size.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy