JavaScript:在嵌套循环中分配给数组

时间:2012-09-01 19:37:27

标签: javascript

我正在编写有关数组的codecademy.com课程。我应该编写嵌套循环,将每个西装的每张卡放在阵列中的一副牌中。

我真的搞砸了。这是我尝试过的一种组合无效的组合。我有点接近的唯一迹象是它返回“52”,因此至少有52个对象进入数组。任何人都可以指出我做错了什么?

   //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);
    }
}

2 个答案:

答案 0 :(得分:2)

每次迭代时,都会向甲板添加一个新数组,如下所示:

cardArray:[[rank [j]]]

当cardArray [0] [0]置位时,它将cardArray [0]覆盖为索引为0且包含rank [j]的数组。相反,将cardArray [0]设置为suit,将cardArray [1]设置为rank。

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

这导致:

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

答案 1 :(得分:1)

您应该为循环计数器使用var声明。您有问题的代码是

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

执行

之类的操作
var foo = "clubs";
foo[0] = "J";

这显然不起作用。我想你想要的是

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