craig
craig

Reputation: 581

Getting from random array

I have the following javascript

 var wordselection = [
{ 'word': "Pomme", "gender": "m", },
{ "word": "Banane", "gender": "f", },
{ "word": "Ananas", "gender": "m", },
{ "word": "Chat", "gender": "f", },
{ "word": "Chien", "gender": "m", },
{ "word": "Poisson", "gender": "f", },

];   

function randomword(){
var chosen = wordselection[Math.floor(Math.random()*wordselection.length)];
document.getElementById("word").innerHTML=chosen;
}

How can I code this so that the it only shows a random "word" (e.g pomme, banane, ananas) or "gender"

At the moment it says [object Object] (because its wrong)

Thanks

Upvotes: 0

Views: 95

Answers (5)

showdev
showdev

Reputation: 29168

I added a parmeter to your randomword() function so that you can specify which type you want to select from: word or gender.

function randomword(type) {
  var chosen=wordselection[Math.floor(Math.random()*wordselection.length)][type];
  document.getElementById("word").innerHTML += "<p>"+chosen+"</p>";
}

randomword('word');
randomword('gender');

http://jsfiddle.net/AESvG/

Upvotes: 2

Simon Arnold
Simon Arnold

Reputation: 16157

Like this http://jsfiddle.net/U6k6G/

wordselection[Math.floor(Math.random()*wordselection.length)].word;

Upvotes: 2

caiocpricci2
caiocpricci2

Reputation: 7788

You didn't specify if you want to show a word or a gender.

Add .word:

var chosen = wordselection[Math.floor(Math.random()*wordselection.length)].word;

or .gender

var chosen = wordselection[Math.floor(Math.random()*wordselection.length)].gender;

Upvotes: 1

Barbara Laird
Barbara Laird

Reputation: 12717

You need to select the word element from the object, intead of just selecting the whole object

http://jsfiddle.net/bhlaird/HKnb3/

var wordselection = [{
    'word': "Pomme",
    "gender": "m",
}, {
    "word": "Banane",
    "gender": "f",
}, {
    "word": "Ananas",
    "gender": "m",
}, {
    "word": "Chat",
    "gender": "f",
}, {
    "word": "Chien",
    "gender": "m",
}, {
    "word": "Poisson",
    "gender": "f",
},

];

function randomword() {
    var chosen = wordselection[Math.floor(Math.random() * wordselection.length)];
    document.getElementById("word").innerHTML = chosen.word;
}

Upvotes: 2

adamb
adamb

Reputation: 4883

Try:

var chosen = wordselection[Math.floor(Math.random()*wordselection.length)].word

Upvotes: 2

Related Questions