How to declare a dynamic local variable in Javascript

前端 未结 7 2178
我在风中等你
我在风中等你 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:29

    Do you need something like this?

    function createVariables(properties, context){
     for( var variable in properties){
        context[variable] = properties[variable ];
     }
    }
    

    So, calling as createVariables(properties, this) will fill the current scope with values from properties.


    <script type="text/javascript">
            var properties = new Object();
            properties["var1"] = "value1";
            properties["var2"] = "value2";
    
            createVariables(properties, this);
    
            document.write("Outside the function : " + var1 + "<br>");
            document.write("Outside the function : " + var2 + "<br>");
        </script>
    
    0 讨论(0)
提交回复
热议问题