Get the value of a variable with with the same nam

2019-09-05 00:45发布

问题:

I have a jQuery widget that outputs a table of contents when invoked.

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.

There criteria for this is quite simple -

  1. Replace {index} with the value of the index parameter that is passed to the function.
  2. Replace and other instance of {.*} (I.e. {whatever} with the matching widget option this.options.whatever.

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.

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.

How can I correct my code?

_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

回答1:

Consider:

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));