我可以添加两个变量来在 JavaScript 中创建一个变量名称吗?

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

本文关键字:一个 创建 变量名 添加 两个 变量 我可以 JavaScript      更新时间:2023-09-26

我是一名新程序员,正在为一个学校项目学习JavaScript。我有两个变量,一个叫做colorA1,另一个叫做playerOneColor。问题是,除了 colorA1(colorA2、colorA3 等)之外,我还有很多变量,所以我试图与之比较的函数无法真正比较 2,因为所有变量都不同。我正在尝试通过添加 2 个变量在 checkColor 函数中重新创建字符串名称。所以我想我的问题是:你能添加 2 个变量来制作一个新的变量名称吗?

感谢您的帮助,如果您对此有任何疑问,请随时提问。我知道我并没有真正完美地表达这一点......

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

这可以通过数组来完成。

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

然后,color[0]将是红色的。