首页 > 关于toString()的一个小问题

关于toString()的一个小问题

概述
toString() 方法返回一个代表该对象的字符串。

语法
object.toString()

当对象需要转换为字符串时,会调用它的toString()方法.。默认情况下,每个对象都会从Object上继承到toString()方法,如果这个方法没有被这个对象自身或者更接近的上层原型上的同名方法覆盖(遮蔽),则调用该对象的toString()方法时会返回"[object type]",这里的字符串type表示了一个对象类型。下面的代码演示了这一点:

var o = new Object();
o.toString(); // 返回了[object Object]

为什么var o=[]; o.toString()返回的是空,而不是【object Array】?


The Array object overrides the toString method of Object. For Array objects, the toString method joins the array and returns one string containing each array element separated by commas. For example, the following code creates an array and uses toString to convert the array to a string.

- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Glob...


Array 的原型中重新定义了 toString() 方法。如果想得到[object Array]的结果,可以像下面这样调用

Object.prototype.toString.call(o)

上面这个方法也是现在最常用的判断一个对象是不是数组的方法


很显然是因为Array.prototype里面重新定义了toString()。如果你把Array.prototype.toString覆盖掉,就可以改成你想要的效果了。

【热门文章】
【热门文章】