简体   繁体   中英

JavaScript: assigning to array in nested loops

I'm working on a codecademy.com lesson on arrays. I'm supposed to write nested loops to put each card of every suit in a deck of cards in an array.

I'm really messing this up. This is one combination that I've tried that doesn't work. The only indication that I have that I'm sort of close is that it returns "52" so at least 52 objects are going into the array. can anyone point out what I'm doing wrong?

   //array 1: the suits
var suits = ["clubs","hearts","diamonds","spades"];

//array 2: the ranks
var ranks = [2,3,4,5,6,7,8,9,10,"J","Q","K","A"];

//using for loops, modify the "deck" array so that it becomes a 
//two-dimensional array that stores every card in the deck; 
//e.g. [1, "clubs"], [2, "clubs"],etc...["A", "spades"]
var deck = [];

for(i = 0; i < suits.length; i++){
    for (j = 0; j < ranks.length; j++){
        var cardArray = [];
        cardArray[0] = suits[i];
        cardArray[0][0] = ranks[j];
        deck.push(cardArray);
    }
}

Each iteration, a new array is being added to deck that looks like the following:

cardArray: [ [ ranks[j] ] ]

When cardArray[0][0] is set, it is overwriting cardArray[0] as an array with index 0 containing ranks[j]. Instead, set cardArray[0] to suits, and cardArray[1] to ranks.

cardArray[0] = suits[i];
cardArray[1] = ranks[j];
deck.push(cardArray);

This results in:

for (var i = 0; i < suits.length; i++){
    for (var j = 0; j < ranks.length; j++){
        var cardArray = [];
        cardArray[0] = suits[i];
        cardArray[1] = ranks[j];
        deck.push(cardArray);
    }
}

You should use a var declaration for your loop counter. Your problematic code is

cardArray[0] = suits[i];
cardArray[0][0] = ranks[j];

which does things like

var foo = "clubs";
foo[0] = "J";

which obviously does not work. I think what you want is

var deck = [];

for(var i = 0; i < suits.length; i++){
    var cardArray = [];
    for (j = 0; j < ranks.length; j++){
        var twoCards = [];
        twoCards[0] = suits[i];
        twoCards[1] = ranks[j];
        cardArray.push(twoCards);
 //     // or the same thing as this loop body, shorter:
 //     cardArray.push([suits[i], ranks[j]]);
    }
    deck.push(cardArray);
}

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