1

I am trying to access the name key of the variable drawnCard in this code and I cannot figure out why it does not work.

Would you mind checking out the end of my Javascript code ?

http://jsbin.com/ohinif/10/edit

Please don't mind the highly probable beginner's coding...

Thanks!!

2
  • 3
    Please put the relevant code directly into your question. Commented Apr 19, 2013 at 15:01
  • @Blazemonger : Hi Blazemonger, thanks, I will keep that in mind for the next ones! Commented Apr 19, 2013 at 19:26

2 Answers 2

1

When splicing the one element out of your array, it is still returning it as an array.

Therefore to get the name you would need to use:

var drawnCard = deck.splice(randomCard, 1);
console.log(drawnCard[0].name) // note the index here

Or you could extract the first item from the splice when pulling it out like so:

var drawnCard = deck.splice(randomCard, 1)[0]; // and the first index here
console.log(drawnCard.name)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! That does it perfectly. I could swear I tried using the first method.. if so I must have done it wrong
0

Do this to your Code

var randomCard = Math.floor(Math.random() * deck.length);
console.log(randomCard)
var drawnCard = deck.splice(randomCard, 1)[0];
console.log(drawnCard.name);

DEMO Here

http://jsbin.com/ohinif/17/edit

2 Comments

Thanks The-Val! Would you mind explaining this syntax of splice() followed by an index? I don't quite get how it reads/works.. Thanks
Ha never mind, I got it, instead of returning an array it returns its first item. So simple but only if you know it's possible :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.