Javascript: How to dynamically add a number to a variable name?

Let's say I need the following:

var numb = $(selector).length; 

And now I want to dynamically create variables based on this:

 var temp+numb = ... 

How can I do this?

Edit:

I know some of you will tell me to use an array. Usually I agreed, but in my case var is already an array, and I see no other solution than creating dynamic names.

+4
source share
2 answers

Javascript variables are bound to objects. Objects take designations . and [] . So you can do:

 var num = 3; window["foo"+num] = "foobar"; console.log(foo3); 

PS - Just because you can do it, it does not mean that you should.

+3
source

Globally (not recommended):

 window["temp"+numb]='somevalue; window.console && console.log(temp3); 

In the area you create, serveride also works, where there is no window area

 var myScope={}; myScope["temp"+numb]="someValue"; window.console && console.log(myScope.temp3); 
+3
source

Source: https://habr.com/ru/post/1502232/


All Articles