获取与字符串值同名的变量的值

Get the value of a variable with with the same name as the value of a string

本文关键字:变量 获取 字符串      更新时间:2023-09-26

我有一个jQuery小部件,它在调用时输出目录。

我想让用户有机会在内容中指定每个独立元素的 ID(默认情况下listElementID: 'contents-{index}'(,所以我在小部件中想出了一个函数来实现这一点。

这方面的标准很简单——

  1. {index}替换为传递给函数的index参数的值。
  2. 替换和{.*}的其他实例(即 {whatever}匹配的小部件选项this.options.whatever

我可以从this.options.listElementID中提取所需的变量,但我似乎找不到一种方法来获取匹配参数/选项的值。

我尝试使用 eval() 来做到这一点(对不起!(,但如果例如 varName = 'index';eval('varName'); 只返回索引,而不是 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));