Reputation: 581
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
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');
Upvotes: 2
Reputation: 16157
Like this http://jsfiddle.net/U6k6G/
wordselection[Math.floor(Math.random()*wordselection.length)].word;
Upvotes: 2
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
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
Reputation: 4883
Try:
var chosen = wordselection[Math.floor(Math.random()*wordselection.length)].word
Upvotes: 2