简体   繁体   中英

Is it possible to store a function call in a dynamic variable?

Also with a dynamic variable name. I tried doing it so:

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;

both dynamicShiftx and dynamicShiftz yield what i need which is positionAx.shift(); and positionAz.shift(); but it doesnt actually shift that value. What am i doing wrong? js newbie btw.

Use an object to group the arrays, then you can generate a string key that lets you access the array you want using bracket notation like so:

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();

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