JavaScript Object toString()
示例
在数组上使用 toString()
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let text = fruits.toString();
自己动手试一试 »
在对象上使用 toString()
const person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};
const keys = person.toString();
自己动手试一试 »
在对象上使用 Object.toString()
const person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};
const keys = Object.toString(person);
自己动手试一试 »
描述
toString()
方法将对象作为字符串返回。
如果无法返回字符串,toString()
方法将返回 "[object Object]"。
Object.toString()
始终返回对象构造函数。
toString()
方法不改变原始对象。
注意
每个 JavaScript 对象都有一个 toString()
方法。
当对象需要作为文本(如在 HTML 中)显示时,或当对象需要用作字符串时,JavaScript 内部会使用 toString()
方法。
通常,你不会在自己的代码中使用它。
浏览器支持
toString()
是 ECMAScript1 (ES1) 的特性。
ES1 (JavaScript 1997) 在所有浏览器中都得到完全支持
Chrome | Edge | Firefox | Safari | Opera | IE |
是 | 是 | 是 | 是 | 是 | 是 |
语法
对象.toString()
参数
无 |
返回值
表示对象的字符串。 或者如果无法返回字符串,则为 "[object type]"。 |