0

This is my Code:

function NewPerson() {
    var count = parseInt($('#HiddenField').html());
    count++;
    $('#HiddenField').html(count);
    Var dynamicVariable = 'Person'+'Count' 
}

I want to define variable on this line Var **dynamicVariable** = 'Person'+'Count'

Now I need to create variable with count number

Charlie
  • 22,886
  • 11
  • 59
  • 90
Saber Motamedi
  • 362
  • 3
  • 27
  • Duplicate of https://stackoverflow.com/questions/5117127/use-dynamic-variable-names-in-javascript – Aakash Dec 05 '17 at 06:41
  • Are you trying to append the variable `count`? Then, use this `var dynamicVariable = 'Person' + count;` – Eddie Dec 05 '17 at 06:42
  • 1
    Possible duplicate of [Use dynamic variable names in JavaScript](https://stackoverflow.com/questions/5117127/use-dynamic-variable-names-in-javascript) – Dawid Zbiński Dec 05 '17 at 06:42
  • thsi is not duplicate , I cant use this answer [link]https://stackoverflow.com/questions/5117127/use-dynamic-variable-names-in-javascript – Saber Motamedi Dec 05 '17 at 06:44
  • dont understand your question. can you elaborate more? like what is that you want to achieve? expected outcome, etc – Sudarpo Chong Dec 05 '17 at 06:45
  • i want Create variable whit Count number, i want genrerate this code: var 1=value; var 2= value;var 3= value;var 4= value; ...... – Saber Motamedi Dec 05 '17 at 06:51

2 Answers2

4

You could also try this.

  var count = 1; //Let this be your count variable.
  var PersonString = "Person" + count; //Building a dynamic name for your variable
  alert(PersonString); //Person1 will be alerted
  window[PersonString] = "One";
  alert(Person1); //One will be alerted.

Click here for the fiddle.

P.S : Here variables created dynamically will have a global scope.

Hrishikesh
  • 632
  • 3
  • 13
2

Usually, the design pattern in this scenario is to use an object.

//These are your variables
var myVar1 = '1';
var myVar2 = '2';

//The object holding all your dynamic variables
var MyVarObj = {};


//Create dynamic variables (object properties)
MyVarObj[myVar1] = 'value1'
MyVarObj[myVar2] = 'value2'


console.log(MyVarObj);   // {1: 'value1', 2: 'value2'}
Charlie
  • 22,886
  • 11
  • 59
  • 90