我有以下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;
}
我如何编码,以便它只显示一个随机的“单词”(例如pomme,banane,ananas)或“gender”
目前它说[object Object](因为它错了)
由于
答案 0 :(得分:2)
尝试:
var chosen = wordselection[Math.floor(Math.random()*wordselection.length)].word
答案 1 :(得分:2)
您需要从对象中选择单词元素,而不是仅选择整个对象
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;
}
答案 2 :(得分:2)
wordselection[Math.floor(Math.random()*wordselection.length)].word;
答案 3 :(得分:2)
我在randomword()
功能中添加了一个参数,以便您指定要从中选择的类型:字词或性别。
function randomword(type) {
var chosen=wordselection[Math.floor(Math.random()*wordselection.length)][type];
document.getElementById("word").innerHTML += "<p>"+chosen+"</p>";
}
randomword('word');
randomword('gender');
答案 4 :(得分:1)
您没有指定是否要显示字词或性别。
添加.word:
var chosen = wordselection[Math.floor(Math.random()*wordselection.length)].word;
或.gender
var chosen = wordselection[Math.floor(Math.random()*wordselection.length)].gender;