javascript - How to create dynamic variables in JS? - Stack Overflow

This is my Code:function NewPerson() {var count = parseInt($('#HiddenField').html());count++;

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 this var 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
 |  Show 1 more ment

2 Answers 2

Reset to default 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.

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744822199a4595684.html

相关推荐

  • javascript - How to create dynamic variables in JS? - Stack Overflow

    This is my Code:function NewPerson() {var count = parseInt($('#HiddenField').html());count++;

    2天前
    70

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信