[英]how to make two variables share a math.random value in javascript
可以將報價隨機化,但現在名稱和報價值不匹配,有沒有辦法使json.name
和json.quote
共享相同的隨機值? 因此,愛因斯坦的報價與Nightingale這個名稱不匹配。
let url =;
$.getJSON( url, function( json ) {
let rand = function getRandom() {
return Math.floor(Math.random() * 4) + 1 ;
}
//console.log(rand());
document.write(" "" + json[rand()].quote +""" + " by "
+json[rand()].name );
});
document.write(" "" + json[rand()].quote +""" + " by "
+json[rand()].name );
每次使用rand()
,它都會生成一個不同的數字,因此json[rand()].quote
和json[rand()].name
會有所不同,因為您使用的是不同的鍵,因此請將rand()
保存在變量中首先,然后使用它,例如:
var randNumber = rand();
document.write(" "" + json[randNumber].quote +""" + " by " +json[randNumber].name );
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.