我使用的是直接从 StackOverflow 源代码复制的字符串格式函数;您现在可以使用以下代码在开发者控制台中对其进行测试:
"Logged in as {tag}, on {guilds} guild{s}".formatUnicorn({ tag: "TAG_HERE", guilds: "GUILD_COUNT", s: "s" });
我正在尝试使用这个完全相同的函数,但总是得到 [object Object]
作为输出。
logger.info("bot", "Logged in as {tag}, on {guilds} guild{s}".format({ tag: client.user.tag, guilds: client.guilds.size, s: client.guilds.size === 1 ? "" : "s" }));
我尝试了 require("util").inspect(...)
返回的对象,但只输出 '[object Object]'
,本质上是完全相同的东西,但用单引号括起来。
这是该函数,如果有帮助的话。我已经重命名了这个问题的一些变量,尽管在测试代码时它是来自 SO 源的直接副本:
String.prototype.format = () => {
let string = this.toString();
if(!arguments.length)
return string;
let type = typeof arguments[0],
replacements = "string" == type || "number" == type ? Array.prototype.slice.call(arguments) : arguments[0];
for(const index in replacements)
string = string.replace(new RegExp("\\{" + index + "\\}", "gi"), replacements[index]);
return string;
}
这可能是一个简单的错误,但有一个简单的解决方案,但我已经工作了很长时间来尝试诊断问题/使其正常工作,但找不到任何可以自己修复的方法。
最佳答案
箭头函数not bind its own 参数
,因此你的函数将无法工作。
从 String.prototype.format = () => {}
更改为 String.prototype.format = function () {}
将为您修复它。
关于javascript - 始终从自定义字符串格式函数获取 "[object Object]"作为输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45517497/