简体   繁体   中英

Can i add two variables to make a variable name in JavaScript?

I'm a new programmer learning JavaScript for a school project. I have two variables, one called colourA1, and another called playerOneColour. The problem is, I have many variables aside from colourA1 (colourA2, colourA3 etc.) so the function that I'm trying to compare it with can't really compare the 2 since all the variables are different. I am trying to recreate the string name in the checkColour function by adding 2 variables. So I guess my question is: can you add 2 variables to make a new variable name?

Thanks for the help, if you have any questions about this, feel free to ask. I know i didn't really word this perfectly...

function drawA1() {
    colourA1 = "red";
}

function checkColour(x) { // <- the HTML passes the id to JavaScript, in this case, it's A1
    alert(variables here); // <- i need this to become colour A1
    alert(playerOneColour);
    if (variables here == playerOneColour) {
        alert("Yes");
    } else {
        alert("No");
    }
}

That can be done with arrays.

var color = ['red', 'green', 'blue'];

Then, color[0] would be red.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM