Javascript Array.prototype.map(回调,thisArg),忽略第二个参数
我正在使用Node.js编写一个小游戏,我希望它能以两种不同的语言提供 为了显示不同游戏模式的翻译列表及其各自的描述,我使用了Javascript Array.prototype.map(回调,thisArg),忽略第二个参数,javascript,node.js,Javascript,Node.js,我正在使用Node.js编写一个小游戏,我希望它能以两种不同的语言提供 为了显示不同游戏模式的翻译列表及其各自的描述,我使用了Array.prototype.map(callback,thisArg),但Node似乎忽略了thisArg参数: sendMessage(translated[channel.id].modeList + modes.filter(a => { if (typeof a === "string") return true; ret
Array.prototype.map(callback,thisArg)
,但Node似乎忽略了thisArg
参数:
sendMessage(translated[channel.id].modeList + modes.filter(a => {
if (typeof a === "string")
return true;
return false;
}).map(translated.modeDesc, translated[channel.id]).join("\n"));
翻译后的:
const translated = {
"chooseLang" : "Choose a language",
"invalidOption" : "Invalid option",
"modeDesc" : mode => {return mode + " : " + "<" + modes[0][mode].join("|") + ">\n = " + this.modeDescs[mode];},
"(channel id)" : global.en
};
节点似乎正在尝试使用不存在的translated.modeDescs
,而不是translated[channel.id].modeDescs
(global.en.modeDescs
):
那么,Node真的忽略了thisArg吗?还是我的方式不对?我该怎么做才能有我想要的行为
提前感谢。使用时,保留词法范围,因此此
指的是已翻译的
对象在中定义的上下文,而不是包含函数引用的实际对象
尝试使用常规函数:
"modeDesc" : function(mode) {return mode + " : " + "<" + modes[0][mode].join("|") + ">\n = " + this.modeDescs[mode];}
看嗯,这很有效。我不知道箭头函数的特殊行为,谢谢。
TypeError: Cannot read property 'mode' of undefined
at Object.ruleDesc (/home/algorythmis/Documents/Game/main.js:89:111)
at Array.map (native)
...
"modeDesc" : function(mode) {return mode + " : " + "<" + modes[0][mode].join("|") + ">\n = " + this.modeDescs[mode];}
var data = translated[channel.id].modeList + modes.filter(a => { ... });
data = Array.prototype.map.call(translated, translated.modeDesc);
sendMessage(data);