首页 > 解决方案 > 将变量的名称存储在数组中

问题描述

我有四个变量,我想使用一个函数来更改它们的值,我可以在其中放入一个存储变量的数组。我正在制作一个使用坐标系的游戏,因此我有四个坐标,我想用 y 轴和 x 轴不断更新。我有一个数组 yAxis,包含所有 y 值和一个数组 xAxis,包含所有 x 值。我想将它们组合成坐标。当然,我可以使用以下代码更新它们:

yAxis = [10, 10, 9, 9];
xAxis = [4, 4, 5, 5];

coordinate1 = "" + yAxis[0] + xAxis[0];
coordinate2 = "" + yAxis[1] + xAxis[1];
coordinate3 = "" + yAxis[2] + xAxis[2];
coordinate4 = "" + yAxis[3] + xAxis[3];

但是,我不想像之前那样更改它们的值,而是想做这样的事情:这个函数将采用下面的数组,coordinateArray 作为 a,yAxis 作为 b,xAxis 作为 c。那么 x 只是一个整数。

test(a, b, c){
  for(x = 0; x < 4; x++){
    a[x] = "" + b[x] + c[x];
  }
}

然后我会这样调用这个函数:

coordinatesArray = [coordinate1, coordinate2, coordinate3, coordinate4];
test(coordinatesArray, yAxis, xAxis);

然后它应该对我运行测试函数的任何数组做什么:

coordinatesArray[0] = "" + yAxis[0] + xAxis[0];
coordinatesArray[1] = "" + yAxis[1] + xAxis[1];
coordinatesArray[2] = "" + yAxis[2] + xAxis[2];
coordinatesArray[3] = "" + yAxis[3] + xAxis[3];

然后例如coordinatesArray[0]应该代表coordinate1.

所以我会创建一个数组来存储变量,这样我就可以轻松地更改要定位的变量。但是问题是,当我运行它时, a[x] 不是变量名,而是它们的值,这意味着这不起作用。所以我的问题是,有没有办法将变量的名称存储在一个数组中,这样我就可以使用类似于我展示的函数来定位它们?我想将变量的名称存储在一个数组中,然后能够使用该名称来定位变量,以便我可以更改它们的值。

标签: javascriptarraysvariables

解决方案


Javascript 中的数组只有索引而不是名称,这就是你需要 Object 的原因:

yAxis = [10, 10, 9, 9];
xAxis = [4, 4, 5, 5];
coordinatesArray = ['coordinate1', 'coordinate2', 'coordinate3', 'coordinate4'];

function test(a, b, c){
    let arrOfObj = [];
    for(let i=0; i < a.length; i++){
        let obj = {};    
        obj[a[i]] = [b[i], c[i]];
        arrOfObj.push(obj);
    }
    return arrOfObj;
}

console.log(test(coordinatesArray,yAxis,xAxis));


推荐阅读