首页 > 解决方案 > 是否可以将函数调用存储在动态变量中?

问题描述

还带有动态变量名。我试着这样做:

let positionAx = [450, 420, 425, 425, 430, 444, 449, 453, 449, 471, 475]; // x + z Coordinates for the following units in order: 
let positionAz = [541, 532, 532, 558, 558, 566, 566, 566, 562, 542, 546]; // CC, melee x2, ranged x2, female x4, cavalry x1, special x1

let dynamicShiftx = ["position" + poppedPosition + "x" + ".shift();"]; 
let dynamicShiftz = ["position" + poppedPosition + "z" + ".shift();"]; 
            
let shiftPositionX = dynamicShiftx;
let shiftPositionZ = dynamicShiftz;

两者都dynamicShiftx产生dynamicShiftz我需要的东西,但它实际上positionAx.shift();并没有改变那个值。positionAz.shift();我究竟做错了什么?js新手顺便说一句。

标签: javascript

解决方案


使用对象对数组进行分组,然后您可以生成一个字符串键,让您可以使用括号表示法访问所需的数组,如下所示:

let positions = {
  Ax: [450, 420, 425, 425, 430, 444, 449, 453, 449, 471, 475],
  Az: [541, 532, 532, 558, 558, 566, 566, 566, 562, 542, 546],
  Bx: ...
  ...
};

let shiftPositionX = positions[poppedPosition + "x"].shift(); 
let shiftPositionZ = positions[poppedPosition + "z"].shift();

推荐阅读