0

I have the following problem: I have to create Veiables like such:

var qrcode_1 = my_CreateQRcode(document.getElementById("qrcode_1"));
var qrcode_2 = my_CreateQRcode(document.getElementById("qrcode_2"));
var qrcode_3 = my_CreateQRcode(document.getElementById("qrcode_3"));
.....

The number of the variables can bie fom 1 to 60.. ist it possible to create these varibles dynamically depending on the amount of actually needed variables.. of have I to degine 60 variables in the code?

3
  • 1
    Use arrays, that’s the case arrays exist for Commented May 17, 2019 at 6:43
  • 1
    What are you trying to achieve by that? Ever heard of for-loops and arrays? Commented May 17, 2019 at 6:44
  • What if you have only 50 qrcode variables but you try to use qrcode_60? That would throw an error. And if you don't know how many there are, how would you know which identifiers to use - you won't be able to determine if there are 5 or 50 of them, if you merely have an unknown amount of variables. Commented May 17, 2019 at 6:47

3 Answers 3

1

You could use an array instead:

var qrcodes = Array.from(
  { length: 60 },
  (_, i) => my_CreateQRcode(document.getElementById('qrcode_' + (i + 1)))
)

But it would be better to use classes instead of numeric-indexed IDs, so you could do something like

var qrcodes = Array.from(
  document.querySelectorAll('.qrcode'),
  my_CreateQRcode // second argument to Array.from is a mapper function
);

Note that array-like structures are zero-indexed, not one-indexed, so, for example, qrcodes[0] will correspond to the first element found and sent through .my_CreateQRcode.

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

Comments

0

If for whatever reason you really need that many variables (as others pointed out, you really should use an array instead), this is how you can achieve that:

for (let i = 60; i > 0; i--) { 
  window["qrcode_"+i] = my_CreateQRcode(document.getElementById("qrcode_"+i)) 
};

Please note that in this specific scenario this is overwriting the already existing variables (the browser automatically creates a global variable for each element with a unique id value under the name of that value, which holds a reference to that element).

Comments

0

You can create class for your html element.

Example:

In HTML->
    <div class="qrcode"></div>....<div class="qrcode"></div>
IN JS ->
    var qrcodes= document.getElementsByClassName(".qrcode");
    for(i=0;i<=qrcodes.length;i++){
           log(qrcodes[i]);
        }

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.