Using counter in variable name Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Using counter in variable name without wasting too much if your time.

The question is published on by Tutorial Guruji team.

This is what I have currently but I cant get v(i) to behave the same as v1. What am I doing wrong? I’ve also tried the piece below which also did not work.

var x = "v" + i;
alert(x);

My main problem is the following:

var v1 = document.getElementById("thing1").innerHTML; // = 100
var v2 = document.getElementById("thing2").innerHTML; // = 150
var v3 = document.getElementById("thing3").innerHTML; // = 200

for (i = 0; i < 4; i++) {
    if ( v(i) != ""){
        alert(v(i));
        }
}

Thanks in advance:)

Answer

What you are trying to do is not easily accomplished. You would have to assign the variable to the window object and then print it from there.

A much better solution is to use your own object or array to handle this:

var v1 = document.getElementById("thing1").innerHTML; // = 100
var v2 = document.getElementById("thing2").innerHTML; // = 150
var v3 = document.getElementById("thing3").innerHTML; // = 200
var array = [v1,v2,v3];
for (i = 0; i < 4; i++) {
    if ( array[i] != ""){
        alert(array[i]);
        }
}
We are here to answer your question about Using counter in variable name - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji