所以我有一个字符串,我想使用 javascript 将其绘制到 HTML5 Canvas 上。我有单独的函数来绘制字母表中的每个字符。
我使用 for 循环遍历字符串中的字符。
let theText = "String"
for (let i = 0; i < theText.length; i++) {
theText[i];
}
我还有字母表中每个字符的函数
function draw_A() {
//code that draws A
}
... a through to x
function draw_X() {
//code that draws X
}
目前我画人物的方法是
for (let i = 0; i < theText.length; i++) {
c = theText[i];
if (c == "A") {
draw_A();
}
... a through to x
else if (c == "X") {
draw_X();
}
}
我知道这种方法效率低下,我也尝试过使用案例,但是,这只是我已经在做的事情的简化版本。
我知道,如果您想在 javascript 中将变量插入字符串中,可以使用 `` 中的 ${} 字符来执行此操作。下面的代码会将变量 'username' 插入到字符串中。
let myString = `Hello ${username}, welcome to this script`;
有没有类似的方法可以用函数来做到这一点。我不想写 26 个 if 或 case 语句来执行我知道应该更简单的事情
最佳答案
只需创建一个查找对象:
const lookup = {
a: draw_A,
/*...*/
x: draw_X
};
然后就可以了
lookup["a"]()
目前你可以在没有查找对象的情况下做得更 hacky(/丑陋):
window["draw_" + "a"]()
关于javascript - 使用变量在 javascript 中调用特定函数而不是 IF 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50647178/