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

6
  • Duplicate of stackoverflow.com/questions/5117127/… Commented Dec 5, 2017 at 6:41
  • Are you trying to append the variable count? Then, use this var dynamicVariable = 'Person' + count; Commented Dec 5, 2017 at 6:42
  • 1
    Possible duplicate of Use dynamic variable names in JavaScript Commented Dec 5, 2017 at 6:42
  • thsi is not duplicate , I cant use this answer [link]stackoverflow.com/questions/5117127/… Commented Dec 5, 2017 at 6:44
  • dont understand your question. can you elaborate more? like what is that you want to achieve? expected outcome, etc Commented Dec 5, 2017 at 6:45

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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'}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.