Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/80.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何在函数调用时将字符串转换为变量名_Javascript_Html_Canvas - Fatal编程技术网

Javascript 如何在函数调用时将字符串转换为变量名

Javascript 如何在函数调用时将字符串转换为变量名,javascript,html,canvas,Javascript,Html,Canvas,我发现自己需要将字符串var(在JavaScript中)转换为变量名,在获取元素时调用该变量名。我自发的解决办法是写: this.name = name; [...] this.context.drawImage(imageRepository.(this.name), this.x, this.y); 但是,这不起作用,返回“意外标记”(“有什么建议吗?”在这种情况下,您需要括号表示法 imageRepository[this.name] 括号表示法计算变量并选择适当的属性。您要查找的是属

我发现自己需要将字符串var(在JavaScript中)转换为变量名,在获取元素时调用该变量名。我自发的解决办法是写:

this.name = name;
[...]
this.context.drawImage(imageRepository.(this.name), this.x, this.y);

但是,这不起作用,返回“意外标记”(“有什么建议吗?”

在这种情况下,您需要括号表示法

imageRepository[this.name]
括号表示法计算变量并选择适当的属性。

您要查找的是属性名称,而不是变量名称。您可以使用括号表示法:

imageRepository[this.name]
在JavaScript中,可以通过两种方式引用属性:使用点表示法和属性名称文字(
obj.foo
),或使用括号表示法和属性名称字符串(
obj[“foo”]
)。在后一种情况下,字符串可以是任何表达式的结果,包括在另一个对象上查找属性(
this.name
)。

Aha,谢谢:-)属性名称,我将确保下次正确引用它