如果我有任何对象,也许是new MyObject()
,我将显示所有内部属性。我该怎么做?
使用alert(new MyObject())
时,结果为[object Object]
。但是我想要所有内部属性。例如...
var MyObject = function() {
this.prop1 = "Hello World";
this.prop2 = "LOL";
this.recursive = this;
this.func = function() { return "func return"; }
}
alert(new MyObject());
在这种情况下,我该如何显示
{ prop1 = "Hello World", prop2 = "LOL", etc... }
最佳答案
您可以编写此函数并将任何对象转换为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"; }
}
观察...当任何属性是递归的时,将不再显示,因为这是无限的。