gpt4 book ai didi

javascript - 如何在 JavaScript 中将任何对象显示为字符串?

转载 作者:行者123 更新时间:2023-11-29 10:08:16 24 4
gpt4 key购买 nike

如果我有任何对象,可能是 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

////For NodeJS remove comment below:
//var window = { };

function ToString(obj) {
clearTimeout(window.ToStringTimeout);

var result;
var ident = arguments.length >= 2 ? arguments[1] : undefined;

if (obj == null) {
result = String(obj);
}

var objString;
try {
objString = obj.toString();
} catch (err1) {
try {
objString = String(obj);
} catch (err2) {
try {
objString = obj + "";
} catch (err3) {
objString = "ERROR CONVERT STRING";
}
}
}

if (!result) {
window.ToStringRecursive = window.ToStringRecursive ? window.ToStringRecursive : [];
if (window.ToStringRecursive.indexOf(obj) >= 0) {
result = obj ? (typeof(obj) == "string" ? "\"" + obj + "\"" : objString) : obj;
} else {
window.ToStringRecursive.push(obj);
}
if (!result) {
switch (typeof obj) {
case "string":
result = '"' + obj + '"';
break;
case "function":
result = obj.name || objString;
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 = objString;
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"; }
}

观察...当任何属性递归时,这不会再次显示,因为这是无限的。

关于javascript - 如何在 JavaScript 中将任何对象显示为字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38733919/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com