Home > Enterprise >  JavaScript interpolation and template literals not allowing me to push to array
JavaScript interpolation and template literals not allowing me to push to array

Time:09-01

I have a need for referencing an array name out of other variables values. Below is a simple program that doesn't push the value into an array. I was hoping someone could determine why. There is no runtime error but when you print the array it has not been pushed. I am creating a 4 person card game that currrently works by having a 2D array with 4 players. I want to deal the cards to P0cards P1Cards.... instead of the 2D players[[],[],[],[]] array. My idea of using $p{i}.push(card) is not working

class Card{
    constructor(suit, value){
        this.value = value;
        this.suit = suit;
    }
}
let deck = [];
let players = [[],[],[],[]];

var p0Cards = [];
var p1Cards = [];
var p2Cards = [];
var p3Cards = [];

function deal(){
    //players 1,2,3,4
    for(let i = 0; i < 4; i  ){
        //cards 1,2,3,4,5,6
        for(let j = 0; j < 6; j  ){
            let card = deck.pop();
            //players[i].push(card);
            `$p{i}.push(card)`;  //this is what I would like to do.
        }
    }
}

CodePudding user response:

Can you make your arr part of an object? Then you can access it with the use of a string.

let myVars = {}
myVars.arr = []
let x = 'arr';
myVars[x].push(2);
myVars.arr.push(3);
console.log(myVars.arr);
// myVars.arr = [2, 3]

  • Related