ga-wdi-exercises / project1

[project] GA- Project 1
3 stars 75 forks source link

issue with splicing the deck and displaying #166

Closed onesick closed 9 years ago

onesick commented 9 years ago

I tried . I expected to happen._____ happened instead.

I tried to splice the deck(52cards) into two 26 cards player hands. But The first player gets length of 26, but the second player's length is 0.

function splitTwo(deck){
  var playerOneHand=deck.splice(0,26);
  var playerTwoHand=deck.splice(26);

  return playerTwoHand;

}

console.log(splitTwo(shuffle()).length);
RobertAKARobin commented 9 years ago

That's because .splice changes the array on which it's called. For example:

var myArray = [0, 1, 2, 3, 4, 5];
myArray.splice(2, 3);
console.log(myArray);
// this prints [0, 1, 5]

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

onesick commented 9 years ago

Yes I just fixed it to this, however, only returns one player's hand. Can you please explain why it's doing this?:

function splitTwo(deck){
  var playerOneHand=deck.splice(0,26);
  var playerTwoHand=deck;

  return playerOneHand, playerTwoHand;

}

console.log(splitTwo(shuffle()));
RobertAKARobin commented 9 years ago

That's because return can only return a single object.

This won't work:

return "hello", "world"

That's trying to return two separate objects.

How could you take two (or more) objects and "package" them inside one object?