Javascript if 语句不执行第二个参数
我有一个 var,它要么是 1,要么是 0,如果它是 1,页面应该转到 cnn.com,如果它是 0,它应该转到 google.com。问题是,当它为 1 或 0 时,它总是会转到 google.com。请访问 http://jsbin.com/ucovef/7 查看正在运行的版本 提前致谢
function random(){
var randomnumber=Math.floor(Math.random()*2)
document.getElementById('randomnumber').innerHTML=(randomnumber);
check_random()
}
function check_random(){
if (randomnumber = 0){
this.location.href ="http://www.cnn.com";
}
if (randomnumber = 1){
this.location.href="http://www.google.com";
}
}
I have a var that is either 1 or 0, if it's 1 the page should go to cnn.com if it's 0 it should go to google.com. Problem is, when it's 1 or 0 it always goes to google.com. Check out the running version at http://jsbin.com/ucovef/7 Thanks in advance
function random(){
var randomnumber=Math.floor(Math.random()*2)
document.getElementById('randomnumber').innerHTML=(randomnumber);
check_random()
}
function check_random(){
if (randomnumber = 0){
this.location.href ="http://www.cnn.com";
}
if (randomnumber = 1){
this.location.href="http://www.google.com";
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您需要:
并且:
表达式
randomnumber = 0
和randomnumber = 1
是赋值表达式,用于分配数字0
和 < code>1 到变量,尽管它们位于if
条件语句内。因此,它始终会转到 google.com,因为所有不等于
0
的内容都是 JavaScript 中的true
表达式。You need:
And:
Expressions
randomnumber = 0
andrandomnumber = 1
are assignment expressions that assign numbers0
and1
to the variables, despite them being inside anif
conditional statement.So, it always goes to google.com because everything not equal to
0
is atrue
expression in JavaScript.您必须使用 == 进行检查。 = 设置值而不是评估它。我还建议将随机数传递给函数。
You have to use == to make a check. = sets the value instead of evaluating it. I would also suggest passing the random number to the function.
你必须使用 == 而不是 = !!!!!!!!!!!!!!!!!!
You must use == not = !!!!!!!!!!!!!!!!
Ben,您正在
check_random
中使用random
中的局部变量。这行不通。试试这个Ben, you are using local variable from
random
incheck_random
. This won't work. Try this