I’m trying to learn JavaScript in Codecademy and one of the things mentioned briefly are “for in” loops. I’ve used them in a few of the exercises, but in this case I can’t get it to work. I could do it with for (i = blah; etc), but I’d like to know what’s wrong with this and if there’s a way to fix it:
//Your three dimensional array from the last exercise probably
//looked something like this:
var hands = [];
hands[0] = [ [3,"H"], ["A","S"], [1,"D"], ["J","H"], ["Q","D"] ];
hands[1] = [ [9,"C"], [6,"C"], ["K","H"], [3,"C"], ["K","H"] ];
//Loop over every dimension in the array, logging out the suit and rank
//of each card in both hands
//1. loop over each hand
for (var hand in hands) {
//2. loop over each card array in each hand
for (var card in hand) {
//3. loop over each rank/suit array for each card in each hand
for (var prop in card) {
//4. log the value of the rank/suit array item
console.log(card[prop]);
}
}
}
The output is 0 0 0, instead of the number and suit. I tried placing console.log() after the first and second loop and I noticed it works correctly in the first, but not in the second one.
Momentarily ignoring the
for-inissue, your inner loops should look like this…Notice that each inner loop needs to explicitly reference the current value of its outer loop. You are iterating over the keys (the variable before
in) instead.To deal with Arrays properly, you should almost always use a
forloop instead offor-in.There are a few reasons for this, which you can find on StackOverflow.
To add clarity to the code, you can cache the current item in a variable…