JavaScript随机数if语句问题 [英] JavaScript random number if statement problem
问题描述
我一直在尝试让系统计算出一个随机数,然后根据生成的数字将一条语句写入屏幕,因此从理论上讲,当出现以下情况时,应该在屏幕上放置一条随机语句页面刷新.
但是,当我刷新页面时,它总是打印第一条语句,而没有其他内容,没有错误,因此我无法弄清为什么会这样.这是我的代码:
Hi, I have been trying to get a system working where a random number is calculated, then a statement is written to the screen depending on the number that was generated, so in theory it should put a random statement on the screen when the page is refreshed.
However, When i refresh the page it always prints the first statement, and no others, There are no error''s so i cannot work out why it is like this. Here is my code:
var fact;
fact = Math.ceil(Math.random()*4)
if (fact = 1) {
document.write('Hi');
}else if(fact = 2){
document.write('Nope');
所以在那之后基本上还有另外两个语句,但是我不明白为什么它只写第一个语句,而没有其他语句.
So basically there are two more statements after that, But i cant understand why it only writes the first statement, and no others.
推荐答案
将其更改为:
Change it into this:
var fact;
fact = Math.ceil(Math.random()*4)
if (fact == 1) {
document.write('Hi');
}else if(fact == 2){
document.write('Nope');
使用==
运算符比较对象,使用=
运算符设置对象的值.
在您的代码中,您没有比较两个变量,但是您在第一个if
语句中将fact
变量设置为1
.
With an ==
operator, you compare objects and with an =
operator, you set the value of an object.
In your code, you didn''t compare the two variables, but you did set the fact
variable to 1
in your first if
statement.
很容易修复-您确定自己看不到它吗?
好的:
It''s pretty easy to fix - are you sure you can''t see it yourself?
Ok:
if (fact = 1) {
成为
if (fact == 1) {
我们都完成了! :laugh:
We''ve all done it! :laugh:
这篇关于JavaScript随机数if语句问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!