你可以写这个功能,任何对象转换为string
。
看JSFiddle
function ToString(obj) {
clearTimeout(window.ToStringTimeout);
var result;
var ident = arguments.length >= 2 ? arguments[1] : undefined;
if (obj == null) {
result = String(obj);
}
if (!result) {
window.ToStringRecursive = window.ToStringRecursive ? window.ToStringRecursive : [];
if (ToStringRecursive.indexOf(obj) >= 0) {
result = obj ? (typeof(obj) == "string" ? "\"" + obj + "\"" : obj.toString()) : obj;
} else {
ToStringRecursive.push(obj);
}
if (!result) {
switch (typeof obj) {
case "string":
result = '"' + obj + '"';
break;
case "function":
result = obj.name || obj.toString();
break;
case "object":
var indent = Array(ident || 1).join('\t'),
isArray = Array.isArray(obj);
result = '{[' [+isArray] + Object.keys(obj).map(
function(key) {
return '\n\t' + indent + key + ': ' + ToString(obj[key], (ident || 1) + 1);
}).join(',') + '\n' + indent + '}]' [+isArray];
break;
default:
result = obj.toString();
break;
}
}
}
window.ToStringTimeout = setTimeout(function() {
delete window.ToStringTimeout;
delete window.ToStringRecursive;
}, 100);
return result;
}
,并使用此:
console.log(ToString(new MyObject()));
为了证明这一点:
{
prop1: "Hello World",
prop2: "LOL",
recursive: [object Object],
func: function() { return "func return"; }
}
检查...当任何财产是递归的这一再显示,因为这是无限的。
'JSON.stringify(object)'...? – Damon
@Damon这是一个循环引用。 –
通常你使用'JSON.stringify(new MyObject())'。请注意,由于循环引用'this.recursive = this',它将不起作用,因为它会永远打印。要解决这个问题,你可以使用第二个参数,参见[这个答案](http://stackoverflow.com/a/9653082/3149020)。 –