获取与字符串值同名的变量值
Get the value of a variable with with the same name as the value of a string
我有一个 jQuery 小部件,它在调用时输出 table 内容。
我想让用户有机会指定内容中每个单独元素的 ID(默认为 listElementID: 'contents-{index}'
),所以我在小部件中想出了一个函数来实现这一点.
这个标准很简单-
- 将
{index}
替换为传递给函数的 index
参数的值。
- 替换
{.*}
的其他实例(即 {whatever}
与匹配的小部件选项 this.options.whatever
。
我可以从 this.options.listElementID
中提取所需的变量,但我似乎无法找到一种方法来获取匹配 parameter/option.
的值
我尝试使用 eval()
来做到这一点(抱歉!),但是如果例如 varName = 'index';
、eval('varName');
只需 returns index ,不是index
参数的值。
如何更正我的代码?
_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));
我有一个 jQuery 小部件,它在调用时输出 table 内容。
我想让用户有机会指定内容中每个单独元素的 ID(默认为 listElementID: 'contents-{index}'
),所以我在小部件中想出了一个函数来实现这一点.
这个标准很简单-
- 将
{index}
替换为传递给函数的index
参数的值。 - 替换
{.*}
的其他实例(即{whatever}
与匹配的小部件选项this.options.whatever
。
我可以从 this.options.listElementID
中提取所需的变量,但我似乎无法找到一种方法来获取匹配 parameter/option.
我尝试使用 eval()
来做到这一点(抱歉!),但是如果例如 varName = 'index';
、eval('varName');
只需 returns index ,不是index
参数的值。
如何更正我的代码?
_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));