嘿,我一直坚持用随机引号和作者编写脚本。 我收到“未定义”消息...是吗? 这是我到目前为止的代码...
<div id="container">
<div id="quote"> </div>
<b class="break">//</b><div id="author"> </div>
</div>
<script>
// set up an array
var myObj, q, a;
myObj = [
{ "quote":"Quote 1", "author":"Author 1" },
{ "quote":"Quote 2", "author":"Author 2" },
{ "quote":"Quote 3", "author":"Author 3" },
{ "quote":"Quote 4", "author":"Author 4" },
];
// calculate a random index number
var arr= [Math.floor((Math.random() * myObj.length-1))];
// display the Quote
document.getElementById("quote").innerHTML=[arr].q;
document.getElementById("author").innerHTML=[arr].a;
</script>
我正在尝试找出需要添加或更改的内容。 任何朝着正确方向的指针都很棒! 欢呼。
答案 0 :(得分:2)
您通过以下几种方式生成随机索引是错误的:
[...]
位创建一个数组-1
上的length
然后,您也错误地查找了条目,创建了一个新数组,并尝试使用arr
对其进行索引。
您使用的属性名称也不正确(q
和a
,而不是quote
和author
)。
您还可以考虑调用myObj
之类的quotes
,因为它是一组引号。
所以:
// calculate a random index number
var index = Math.floor(Math.random() * quotes.length);
// display the Quote
document.getElementById("quote").innerHTML = quotes[index].quote;
document.getElementById("author").innerHTML = quotes[index].author;
实时示例:
// set up an array
var quotes = [
{ "quote":"Quote 1", "author":"Author 1" },
{ "quote":"Quote 2", "author":"Author 2" },
{ "quote":"Quote 3", "author":"Author 3" },
{ "quote":"Quote 4", "author":"Author 4" },
];
function showQuote() {
// calculate a random index number
var index = Math.floor(Math.random() * quotes.length);
// display the Quote
document.getElementById("quote").innerHTML = quotes[index].quote;
document.getElementById("author").innerHTML = quotes[index].author;
}
showQuote();
document.getElementById("again").addEventListener("click", showQuote);
<div id="container">
<div id="quote"> </div>
<b class="break">//</b>
<div id="author"> </div>
</div>
<input type="button" id="again" value="Again">
答案 1 :(得分:1)
抱歉,这是完全错误的写信。
尝试:
sc.parallelize([my_json])
答案 2 :(得分:1)
您应该执行以下操作:
var randomQuote = myObj[Math.floor((Math.random() * myObj.length))]
console.log(randomQuote.quote, randomQuote.author);
答案 3 :(得分:-1)
演示:https://codepen.io/creativedev/pen/vrzJjd 您可以这样操作:
var myObj, q, a;
myObj = [
{ "quote":"Quote 1", "author":"Author 1" },
{ "quote":"Quote 2", "author":"Author 2" },
{ "quote":"Quote 3", "author":"Author 3" },
{ "quote":"Quote 4", "author":"Author 4" },
];
// calculate a random index number
var arr= [Math.floor((Math.random() * myObj.length-1))];
// display the Quote
document.getElementById("quote").innerHTML=myObj[arr].quote;
document.getElementById("author").innerHTML=myObj[arr].author;