Using counter in variable name

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]);
        }
}

Leave a Reply

Your email address will not be published. Required fields are marked *