Math.random函数在带有if语句的javascript中无法正常工作
在我的函数中,我使用Math.random生成一个随机数,然后使用if语句,我希望它在滚动超过1时显示警报。在这种情况下,这是我的代码:Math.random函数在带有if语句的javascript中无法正常工作,javascript,Javascript,在我的函数中,我使用Math.random生成一个随机数,然后使用if语句,我希望它在滚动超过1时显示警报。在这种情况下,这是我的代码: function Enemy(x,y){ this.x=x; this.y=y; this.speed=5; this.width=30; this.height=30; return Math.floor((Math.random() * 100) +
function Enemy(x,y){
this.x=x;
this.y=y;
this.speed=5;
this.width=30;
this.height=30;
return Math.floor((Math.random() * 100) + 1);
if (Math.random() > 1) {
alert(booyah);
}
}
现在,我打开页面时没有收到任何警报。如果我在控制台中使用敌人();我得到了一个数字,所以工作正常
return Math.floor((Math.random() * 100) + 1);
if (Math.random() > 1) {
alert(booyah);
}
在返回语句之后不能执行任何代码 如果它已经返回到if块上面,它就不会进入if块。一旦函数命中return语句,它就是函数的结尾,所以if语句被忽略。尝试将math.random赋值给变量,并在返回之前发出if语句
function Enemy(x,y){
this.x=x;
this.y=y;
this.speed=5;
this.width=30;
this.height=30;
var random = Math.random();
if (random > 1) {
alert(booyah);
}
return Math.floor((random * 100) + 1);
}
它不工作是因为
random()
从来都不大于1,还是因为它在return
语句之后?或者,booyah
没有定义?它应该做什么?只有三行代码就有这么多bug。。。