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

标签 javascript jquery variables eval

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

我想让用户有机会指定内容中每个单独元素的 ID(默认为 listElementID: 'contents-{index}'),因此我在小部件中提供了一个函数来实现此目的。

这个标准非常简单 -

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

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

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

关于javascript - 获取与字符串值同名的变量的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35175528/

相关文章:

javascript - 如何使用 knockout 自动从 JSON 加载数组

javascript - Android 浏览器 JavaScript 无法正确测量高度

javascript - Angular 2 显示混合元素数组

javascript - 有没有更优雅的方法来检测触摸事件支持并分配 "click"或 "touchend"事件?

javascript - 如何在图像之间留出空间?

javascript - 如何获取jquery中选中的复选框对应的span值

jquery - 验证器错误消息使提交按钮从页面上消失

php - 在 PHP 中调用函数时使用临时变量

c - 编译器在c中分配垃圾值的贡献

bash——在运行之间存储变量的更好方法?