How to declare a dynamic local variable in Javascript

前端 未结 7 2175
我在风中等你
我在风中等你 2021-02-04 08:37

I want to create a local variable dynamically. JavaScript: Dynamically Creating Variables for Loops is not exactly what I am looking for. I dont want an array. I want to access

相关标签:
7条回答
  • 2021-02-04 09:10

    Depending on the scope you'd like the variables to have, this could be accomplished in a few different ways.

    Global scope

    To place the variables in the global scope, you could use window[varName]:

    function createVariables(variables) {
        for (var varName in variables) {
            window[varName ] = variables[varName ];
        }
    }
    
    createVariables({
        'foo':'bar'
    });
    console.log(foo); // output: bar
    

    Try it: http://jsfiddle.net/nLt5r/

    Be advised, the global scope is a dirty, public place. Any script may read, write, or delete variables in this scope. Because of this fact, you run the risk of breaking a different script that uses the same variable names as yours, or another script breaking yours.

    Function scope (using this)

    To create variables in a function's scope (this.varName), you can use bind:

    var variables = {
        'foo':'bar'
    };
    var func = function () {
        console.log(this.foo);
    };
    var boundFunc = func.bind(variables);
    boundFunc(); // output: bar
    

    Try it: http://jsfiddle.net/L4LbK/

    Depending on what you do with the bound function reference, this method is slightly vulnerable to outside modification of the variables. Anything that can access boundFunc can change or refer to the value of the values by using boundFunc.varName = 'new value'; This may be to your advantage, depending on use case.

    Function scope (using arguments)

    You can use apply to pass an array of values as arguments:

    var variables = [
        'bar'
    ];
    var func = function (foo) {
        console.log('foo=', foo);
    };
    func.apply(null, variables);
    

    Try it: http://jsfiddle.net/LKNqd/

    As arguments are ephemeral in nature, nothing "outside" could interfere with or refer back to the values, except by modifying the variable array and re-calling the function.

    Global scope as temporary

    And here's a small utility function that will make temporary use of the global scope. This function is dangerous to code that also uses the global scope -- this could blast over variables that other scripts have created, use at your own risk:

    var withVariables = function(func, vars) {
       for (var v in vars){
           this[v] = vars[v];
       }
       func();
       for (var v in vars){
           delete this[v];
       }
    };
    
    // using an anonymous function
    withVariables(
        function () {
            console.log('anonymous: ', foo);   
        },
        {
            'foo':'bar'   
        }
    ); // output: bar
    
    // using a function reference
    var myFunction =function () {
        console.log('myFunction: ', foo);   
    };
    withVariables(myFunction, {
        'foo':'bar'   
    }); // output: bar
    
    console.log(foo); // output: undefined
    

    Try it: http://jsfiddle.net/X3p6k/3/

    Documentation

    • bind on MDN - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
    • apply on MDN - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply
    • window on MDN - https://developer.mozilla.org/en-US/docs/Web/API/Window
    0 讨论(0)
  • 2021-02-04 09:13

    The example below demonstrates how with gets a value from the object.

    var obj = { a : "Hello" }
    with(obj) {
      alert(a) // Hello
    }
    

    But I want to notice: with is deprecated!

    0 讨论(0)
  • 2021-02-04 09:17

    I have written short code snippet which will create both local and global variable dynamically

    function createVar(name,dft){
     this[name] = (typeof dft !== 'undefined')?dft:"";
    }
    
    createVar("name1","gaurav"); // it will create global variable
    createVar("id");// it will create global variable
    
    alert(name1);
    alert(id);
    function outer(){
     var self = this;
      alert(self.name1 + " inside");
    }
    createVar.call(outer,"name1","saurav"); // it will create local variable
    outer.call(outer); // to point to local variable.
    outer(); // to point to global variable
    alert(name1);
    

    hope this helps Regards Gaurav Khurana

    0 讨论(0)
  • 2021-02-04 09:21

    since you are wanting the scope of where the function is being called pass this to the function

    var properties = new Object();
    properties["var1"] = "value1";
    properties["var2"] = "value2";
    function createVariables(context) {
         for(i in properties) { 
             context[i] = properties[i];
         }   
    }
    createVariables(this);
    console.log( var1 );
    
    0 讨论(0)
  • 2021-02-04 09:26

    Here is working sample based on Chris Baker answer: Function scope (using arguments)

        function myFn() {
          function keyList(params) {
            var str = '';
            for (var key in params) {
              if (params.hasOwnProperty(key)) {
                str += ',' + key;
              }
            }
            return str.length ? str.substring(1) : str;
          }
    
          function valueList(params) {
            var list = [];
            for (var key in params) {
              if (params.hasOwnProperty(key)) {
                list.push(params[key]);
              }
            }
            return list;
          }
          var params = {
            'var1': 'value1',
            'var2': 'value2'
          };
          var expr = 'document.write("Inside the function : " + var1 + "<br>")'
          var fn;
          eval('var fn = function(' + keyList(params) + '){' + expr + '};');
          fn(valueList(params));
        }
    
        myFn();

    0 讨论(0)
  • 2021-02-04 09:28

    This answer is more or less the same as several answers above but here with a simplified sample, with and without using eval. First using eval (not recommended):

    var varname = 'foo';  // pretend a user input that
    var value = 42;
    eval('var ' + varname + '=' + value);
    

    And alternatively, without using eval:

    var varname = prompt('Variable name:');
    var value = 42;
    this[varname] = value;
    

    I hope this helps.

    Source: https://www.rosettacode.org/wiki/Dynamic_variable_names#JavaScript

    0 讨论(0)
提交回复
热议问题