How to declare a dynamic local variable in Javascript

前端 未结 7 2176
我在风中等你
我在风中等你 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: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 + "
    ")' var fn; eval('var fn = function(' + keyList(params) + '){' + expr + '};'); fn(valueList(params)); } myFn();

提交回复
热议问题