gpt4 book ai didi

javascript - 从数组中随机选择

转载 作者:行者123 更新时间:2023-12-03 07:20:56 27 4
gpt4 key购买 nike

我正在尝试创建一个网站,它可以从数组中随机选择一些内容来造句。它应该从 objectArray 中选择一个随机项目,并通过 divdocument.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>

最佳答案

您将元素的 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>

关于javascript - 从数组中随机选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36212963/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com