包含多条信息的数组 - Javascript

时间:2015-05-10 10:38:21

标签: javascript arrays random

我有这个javascript代码:

var randomwordz = [

{word: 'Sweets', image: 'sweets.jpg'}, 
{word: 'Chocolate', image: 'chocolate.jpg'}, 
{word: 'Snow', image: 'snow.jpg'},
{word: 'Pineapple', image: 'pineapple.gif'},
{word: 'Juice', image: 'j.jpg'},
{word: 'Egg', image: 'egg.gif'},
{word: 'Cheese', image: 'cheese.gif'},
{word: 'Chicken', image: 'chick.jpg'}, 
{word: 'Veg', image: 'veg.gif'}];

randomWords[0].word
randomWords[0].image

randomWords[1].word
randomWords[1].image

randomWords[2].word
randomWords[2].image

randomWords[3].word
randomWords[3].image

randomWords[4].word
randomWords[4].image

randomWords[5].word
randomWords[5].image

randomWords[6].word
randomWords[6].image

randomWords[7].word
randomWords[7].image

randomWords[8].word
randomWords[8].image

var randoms = randomWords[Math.floor(Math.random()*randomWords.length)];

document.getElementById('randomwords').innerHTML = randoms;

我的随机单词显示在我的页面上,但自从我在显示随机单词时将图像添加到数组后,它显示 - [对象对象]而不是我的随机单词。

有谁知道为什么以及如何只展示随机单词。我需要将单词和图像配对以用于代码的下一部分。

请原谅我对Javascript

的新知识缺乏

1 个答案:

答案 0 :(得分:4)

您有对象数组,您现在需要在选择索引后从对象中选择所需的属性

document.getElementById('randomwords').innerHTML = randoms.word;

// and you may want to do something like this for your image
document.getElementById('randomimages').src= randoms.image;