1

I'm creating a spelling bee web app for the school I work at. My idea is to have the students click on a button, which will randomly select and play the audio of a word. Then, they will write the word on the form and submit for correction.

This is my prototype code

1st, an object with the words names and audio files.

var words = {}
words.carrot = {
audio : new Audio ('http://dictionary.cambridge.org/media/english-portuguese/uk_pron/u/ukc/ukcar/ukcarap002.mp3'),
name : "CARROT"
}
words.ball = {
audio : new Audio ('http://dictionary.cambridge.org/us/media/english/us_pron/b/bal/ball_/ball.mp3'),
name : "BALL"
}

Then, a function that randomly selects a property of the object. It would be called by clicking on a button.

var play = function(){

var list = Object.keys(words);

var randomWord = list[Math.floor(Math.random()*list.length) ];
}

So far, so good.

What I don't manage to do is to incorporate the resulting word back into the objects syntax. For the sake of testing, I tried the following:

document.getElementById("demoparagraph").innerHTML = randomWord

And it perfectly shows one of the properties.

But this doesn't work: words.randomWord.audio. It returns "undefined".

Whereas words.carrot.audio works just fine.

Evan
  • 37
  • 4
  • 1
    You're misunderstanding javascript objects. words.carrot works because carrot is a property. You have created an object with two properties, carrot and ball. Not an array with two options. – samuelmr Apr 25 '16 at 15:06
  • 1
    You need to use bracket notation `words[randomWord].audio` – jcubic Apr 25 '16 at 15:08
  • The bracket notation worked! Thanks! – Evan Apr 25 '16 at 15:16

0 Answers0