2017-08-05 17 views
0

我正在使用直接從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(...) ING的返回的對象,但只是輸出'[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; 
} 

這可能是一個簡單的錯誤有一個簡單的解決方案,但我已經很努力一段時間來嘗試診斷問題/讓它工作,但沒有找到自己解決的問題。

+0

爲什麼你使用「typeof arguments [0]」? –

+0

該部分直接從SO代碼複製。 ¯\\ _(ツ)_ /¯ – ffxhand

回答

2

箭頭功能確實not bind its ownarguments所以你的功能將無法正常工作。

String.prototype.format =() => {}更改爲String.prototype.format = function() {}將爲您解決。

+0

太好了,修復了它!永遠不會想到它自己。謝謝! – ffxhand

0

它是因爲你使用的是this.toString();this是json對象。

嘗試:

String.prototype.format = function() { ... 

代替:

String.prototype.format =() => { ... 
相關問題