How to declare a dynamic local variable in Javascript

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

提交回复
热议问题