Javascript - 使用字符串连接设置变量 [英] Javascript - set a variable using concatenation of strings
问题描述
是否可以通过将两个字符串连接在一起形成名称来设置变量?
Is it possible to set a variable by concatenating two strings together to form the name?
如果可能的话,我想根据用户点击的对象的类名确定要设置的变量。我知道我可以硬编码一堆if / else if语句,但如果我可以间接引用变量,那将会非常酷。我在想这样的事情:
If at all possible I'd like to determine what variable to set based on the class names of the objects that the user clicks. I know I can hard code a bunch of if/else if statements, but it would be really cool if I could reference the variables indirectly. I was thinking something like this:
var owner_read;
var group_read;
function setVariableIndirectly(object){
var second = object.className; // returns "read"
var first = object.parentElement.className; // returns "group"
first + "_" + second = "set this as the new variable";
}
有没有办法做到这一点??
Is there any way of doing this??
编辑:
这是数据来自的html。
Here's the html that the data is coming in from.
<p class="owner">
<span class="read" onclick="permissionClick(this)">r</span>
<span class="write" onclick="permissionClick(this)">w</span>
<span class="execute" onclick="permissionClick(this)">x</span>
</p>
推荐答案
目前尚不清楚你要完成的是什么,但您可以按名称访问变量作为对象的属性。
It's not clear exactly what you're trying to accomplish, but you can access variables by name as properties of an object.
// this is the container to hold your named variables
// (which will be properties of this object)
var container = {};
function setVariableIndirectly(obj){
var second = obj.className; // returns "read"
var first = obj.parentNode.className; // returns "group"
// this is how you access a property of an object
// using a string as the property name
container[first + "_" + second] = "set this as the new variable";
// in your example container["read_group"] would now be set
}
如上所示,将变量放在您自己的容器对象上可能更好,但您也可以通过窗口
对象上的属性访问全局变量。
It's probably better to put your variables on your own container object as shown above, but you can also access global variables via properties on the window
object.
这篇关于Javascript - 使用字符串连接设置变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!