Javascript 如何将函数随机数保存在变量中
我想这样做:Javascript 如何将函数随机数保存在变量中,javascript,Javascript,我想这样做: var randomNum = Math.floor(Math.random() * 10 + 1); console.log("What is the answer of: " + randomNum + " + " + randomNum + "?"); console.log("What is the answer of: " + randomNum + " + " + randomNum + "?"); console.log("What is th
var randomNum = Math.floor(Math.random() * 10 + 1);
console.log("What is the answer of: " + randomNum + " + " + randomNum + "?");
console.log("What is the answer of: " + randomNum + " + " + randomNum + "?");
console.log("What is the answer of: " + randomNum + " + " + randomNum + "?");
console.log("What is the answer of: " + randomNum + " + " + randomNum + "?");
在控制台内部,我希望它能够:
答案是什么:5+6?
当我们刷新页面时,我们应该得到另一个数字,例如:
答案是什么:3+1?
等
正常随机函数,但将其分配给变量;
因为当我这么做的时候,它只会一直打印相同的号码?
insde我的控制台:
答案是什么:1+1?
第二次刷新
答案是什么:3+3?
第三次刷新:
答案是什么:2+2?
以此类推,两个单元格的值相同?
我可以通过基本结构在不干燥的情况下修复它(不要重复您自己):
//var randomNum = Math.floor(Math.random() * 10 + 1);
console.log("What is the answer of: " + Math.floor(Math.random() * 10 + 1) + " + " + Math.floor(Math.random() * 10 + 1) + "?");
但正如你所知,也许我正在做一个大项目,所以我不应该重复我自己,对吗?这将起作用,你需要使它成为一个功能
var randomNum = () => Math.floor(Math.random() * 10 + 1);
然后,当您这样做时,可以将其用作
randomNum()
:var randomNum=Math.floor(Math.random()*10+1)代码>,首先计算表达式的右侧,然后将其分配到randomNum。所以ofc将保持不变
把它变成一个函数:
randomNum=()=>Math.floor(Math.random()*10+1)
您只需创建一个函数,创建两个唯一的随机数,并在触发DOMContentLoaded
事件时调用该函数:
//在DOM完全加载和解析时调用随机数函数
addEventListener('DOMContentLoaded',init)
函数init(){
//我们必须在此处创建两个唯一的随机数(而不仅仅是一个):
常数a=数学地板(数学随机()*10+1),
b=数学楼层(数学随机()*10+1);
log(`${a}+${b}=${a+b}`);
}
让它成为一个你一直在调用的函数:console.log(“…”+rand()+“…”+rand())
。我可以知道我为什么被否决吗?