简体   繁体   English

如何传递字符串并将其用作变量名?

[英]How can I pass in a string and use that as a variable name?

I have a variable such as: 我有一个变量,例如:

var startX = 20
var startY = 30

I want to call a function such as: 我想调用一个函数,例如:

onClick="myFunction('startX')"
or
onClick="myFunction('startY')"

myFunction(passedVar){
}

So passedVar = 'startX' or 'startY' and I then need to reference the variable of the same name and get it's value (20 or 30) 因此,passedVar ='startX'或'startY',然后我需要引用相同名称的变量并获取其值(20或30)

In Powershell I'd do a: 在Powershell中,我将执行以下操作:

get-variable($passedVar) -value

which would see what's in passedVar and then look for a variable with that name and give me the value. 它将看到passedVar中的内容,然后查找具有该名称的变量并给我值。

Does that make sense? 那有意义吗?

Thanks! 谢谢!

Global variables are just properties of the window object. 全局变量只是window对象的属性。 You could try 你可以试试

var val = window[passedVar];

You simply have to omit the single quotes; 您只需要省略单引号即可; it is not required. 不需要。

onClick="myFunction(startX)" or onClick="myFunction(startY)" onClick =“ myFunction(startX)”或onClick =“ myFunction(startY)”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM