Simplify multiple variables in JavaScript

How to simplify a set of vars?

var q1 = 0; var q2 = 0; var q3 = 0; var q4 = 0; var q5 = 0; var q6 = 0; var q7 = 0; var q8 = 0; var q9 = 0; var q10 = 0; var counter = 0; 

or how is it?

 var q1 = 0, q2 = 0, q3 = 0, q4 = 0, q5 = 0, q6 = 0, q7 = 0, q8 = 0, q9 = 0, q10 = 0, counter = 0; 

Is there any way?

+5
source share
4 answers

If you use series variables. The best option is an array

  var q=[0,0,0,0,0,0,0,0,0,0] , counter=0; 
+1
source

Please check the answers in this post:

How to declare and use dynamic variables in javascript?

 for(var i=1;i<=10;i++) {window['q' + i] = 0}; var counter =0; 
0
source

Try using the following code:

 for (var q = 1; q<10; q++) { // do what you want //ie. // counter = counter + q; } 
0
source

Probably the easiest

 var q1 = q2 = q3 = q4 = q5 = q6 = q7 = q8 = q9 = q10 = counter = 0; 

But wait

The presence of these variables can lead to further problems.

You have an array with all of these values. In order to refer to them, you must call them every time =. But with arrays, you may be able to loop them and access them with an index.

-1
source

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


All Articles