为什么Object.prototype.toString返回[object Object] [英] why Object.prototype.toString return [object Object]

查看:105
本文介绍了为什么Object.prototype.toString返回[object Object]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码如下所示

var obj = { name: 'John' }
var x = obj.toString();// produce "[object Object]"

alert(x)

我想知道为什么实现Object.prototype.toString返回[object Object],为什么不实现Object.prototype.toString返回"{name: 'John'}"吗?

i want to know why Object.prototype.toString is implemented to return [object Object] and why It's not implemented to return "{name: 'John'}" ?

推荐答案

有关规范的说明,请参见@Leo和@Joel Gregory的答案.您可以使用JSON.stringify显示对象的内容,例如:

See answers from @Leo and @Joel Gregory for an explanation from the spec. You can display an objects' contents using JSON.stringify, e.g.:

const log = (...args) => document.querySelector("pre").textContent += `${args.join("\n")}\n`;
const obj = { name: 'John' }

log(obj.toString());
log(JSON.stringify(obj));

<pre></pre>

这篇关于为什么Object.prototype.toString返回[object Object]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆