简体   繁体   中英

JavaScript interpolation and template literals not allowing me to push to array

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.
        }
    }
}

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]

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