获取与字符串名称同名的变量的值 [英] Get the value of a variable with with the same name as the value of a string
问题描述
我有一个jQuery窗口小部件,该窗口小部件在被调用时会输出一个目录.
I have a jQuery widget that outputs a table of contents when invoked.
我想让用户有机会在内容中指定每个独立元素的ID(默认为listElementID: 'contents-{index}'
),因此我在小部件中提供了一个函数来实现此目的.
I'd like to give users the oppurtunity to specify the ID of each individal element within the contents (listElementID: 'contents-{index}'
by default), so I've come up with a function within the widget to achieve this.
有很简单的条件-
- 用传递给函数的
index
参数的值替换{index}
. - 替换
{.*}
的其他实例(即{whatever}
,并带有匹配的小部件选项this.options.whatever
.
- Replace
{index}
with the value of theindex
parameter that is passed to the function. - Replace and other instance of
{.*}
(I.e.{whatever}
with the matching widget optionthis.options.whatever
.
我可以从this.options.listElementID
中提取所需的变量,但似乎找不到找到匹配参数/选项值的方法.
I can extract required variables from this.options.listElementID
, but I can't seem to find a way to then get the value of the matching parameter/option.
我尝试使用eval()
来做到这一点(对不起!),但是例如,如果varName = 'index';
,eval('varName');
只是返回 index ,而不是index
参数的值
I've tried to do this using eval()
(sorry!), but if for example varName = 'index';
, eval('varName');
simply returns index, not the value of the index
parameter.
如何纠正我的代码?
_getContnetsLineID : function(index){
var vars = (this.options.listElementID.match(/{.*}/g) || []),
ID = this.options.listElementID;
for(var i = 0; i < vars.length; i++){
var varName, // The name of the variable to grab the value from
value; // The value to replace the placehoder with
varName = vars[i].replace('{', '').replace('}', ''); // Remove the '{' and '}' characters from the 'varName'
if(varName == 'index'){ // Attempt to grab the value from a variable that matches the string 'varName'
value = eval('varName');
} else {
value = eval('this.options.varName');
}
ID = ID.replace(vars[i], value); // Replace the placeholder with the appropriate value
}
return ID;
} // _getContnetsLineID
推荐答案
考虑:
this.options = {
listElementID: "foobar-{index}-{whatever}",
whatever: "hi"
};
_getLineID = function (index) {
return this.options.listElementID.replace(/{(.+?)}/g, function (_, name) {
return name === 'index' ? index : this.options[name];
});
}
document.write(_getLineID(25));
这篇关于获取与字符串名称同名的变量的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!