Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialJacek Skrzypek
5,040 PointsCould I use the for...in loop in createDeck()?
Hi, i tried to use the for in loop like this:
function createDeck() {
var suites = ['♠︎','♣︎','♥︎','♦︎'];
var ranks = ['Ace','King','Queen','Jack','10','9','8','7','6','5','4', '3','2'];
var deck = [];
// add your code below here:
for (let suit in suites) {
for (let rank in ranks) {
let card = [suit, rank];
deck.push(card);
}
}
shuffle(deck);
return(deck);
}
but it gave me array of indexes.
Finally I did it the other way:
function createDeck() {
var suites = ['♠︎','♣︎','♥︎','♦︎'];
var ranks = ['Ace','King','Queen','Jack','10','9','8','7','6','5','4', '3','2'];
var deck = [];
// add your code below here:
for (var i = 0; i < suites.length; i++) {
for (var y = 0; y < ranks.length; y++) {
let card = [ranks[y], suites[i]];
deck.push(card);
}
}
shuffle(deck);
return(deck);
}
// 6. Call the createDeck() function and store the results in a new variable named myDeck
var myDeck = createDeck();
//* 7. Use a for loop to loop through the deck and list each card in the order the appear in the newly shuffled array. Use the log() method to print out a message like this, once for each card:
//"7 of ♥.︎"
*//
console.log(myDeck)
for (var i = 0; i < myDeck.length; i++) {
console.log(myDeck[i][0] + " of " + myDeck[i][1])
}
Could someone explain, how I could use the for...in loop in this case?
Cheers, JS
1 Answer
KRIS NIKOLAISEN
54,971 PointsUse the indexes like you did in the second code
for (let suit in suites) {
for (let rank in ranks) {
let card = [suites[suit], ranks[rank]];
deck.push(card);
}
}
Jacek Skrzypek
5,040 PointsJacek Skrzypek
5,040 PointsGreat, thank you!