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
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
Share Improve this question edited Dec 5, 2017 at 7:32 Charlie 23.9k12 gold badges63 silver badges95 bronze badges asked Dec 5, 2017 at 6:39 Saber MotamediSaber Motamedi 4499 silver badges31 bronze badges 6- Duplicate of stackoverflow./questions/5117127/… – Aakash Commented Dec 5, 2017 at 6:41
-
Are you trying to append the variable
count
? Then, use thisvar dynamicVariable = 'Person' + count;
– Eddie Commented Dec 5, 2017 at 6:42 - 1 Possible duplicate of Use dynamic variable names in JavaScript – Dawid Zbiński Commented Dec 5, 2017 at 6:42
- thsi is not duplicate , I cant use this answer [link]stackoverflow./questions/5117127/… – Saber Motamedi Commented Dec 5, 2017 at 6:44
- dont understand your question. can you elaborate more? like what is that you want to achieve? expected oute, etc – Peter Stark Commented Dec 5, 2017 at 6:45
2 Answers
Reset to default 4You 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.
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'}