0

我有以下 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] (因为它错了)

谢谢

4

5 回答 5

2

尝试:

var chosen = wordselection[Math.floor(Math.random()*wordselection.length)].word
于 2013-10-08T16:01:55.627 回答
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;
}
于 2013-10-08T16:02:16.763 回答
2

像这样http://jsfiddle.net/U6k6G/

wordselection[Math.floor(Math.random()*wordselection.length)].word;
于 2013-10-08T16:03:42.847 回答
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');

http://jsfiddle.net/AESvG/

于 2013-10-08T16:03:59.977 回答
1

您没有指定是否要显示单词或性别。

添加.word:

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

或 .gender

var chosen = wordselection[Math.floor(Math.random()*wordselection.length)].gender;
于 2013-10-08T16:03:10.523 回答