从数组中随机选择

时间:2016-03-25 02:04:13

标签: javascript arrays random

我正在尝试创建一个网站,从数组中选择随机内容来制作句子。它应该从objectArray中选择一个随机项,然后通过div document.getElementById()

显示它

代码

<script>
    var objectArray = ["computer", "iphone", "duck", "candle", "oven", "sofa", "curtain", "blanket", "star", "piano", "turtle", "fluffiness", "door", "pillow", "funny face", "lamp", "healthy heart", "rainbow", "lamp", "clock", "coat", "just luck", "stop sign", "window"];
    var randObject = objectArray[Math.floor(Math.random() * objectArray.length)];

    document.getElementById("Objecto").innerHTML = "randObject";    
</script>

<center>
    <div id="Objecto"></div>
</center>

1 个答案:

答案 0 :(得分:1)

您将元素的innerHTML设置为字符串文字"randObject",而不是变量randObject的内容。请改用:

document.getElementById("Objecto").innerHTML = randObject;

这是一个完整的代码段:

var objectArray = ["computer", "iphone", "duck", "candle", "oven", "sofa", "curtain", "blanket", "star", "piano", "turtle", "fluffiness", "door", "pillow", "funny face", "lamp", "healthy heart", "rainbow", "lamp", "clock", "coat", "just luck", "stop sign", "window"];
var randObject = objectArray[Math.floor(Math.random() * objectArray.length)];

document.getElementById("Objecto").innerHTML = randObject;  
<center>
    <div id="Objecto"></div>
</center>