数学.随机函数不能正常工作在javascript与if语句

Math.random function not properly working in javascript with if statement

本文关键字:javascript 语句 if 工作 函数 随机 不能 常工作 数学      更新时间:2023-09-26

在我的函数中,我使用数学生成一个随机数。随机的,然后加上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) + 1);
            if (Math.random() > 1) {
                alert(booyah);
            }
    }

现在,当我打开页面时,我没有得到任何提示。如果我在控制台使用Enemy();我得到一个数字,这很好

 return Math.floor((Math.random() * 100) + 1);
            if (Math.random() > 1) {
                alert(booyah);
            }

任何代码都不能在return语句之后执行;

一旦函数命中return语句,它就是函数的结束,因此if语句被忽略。尝试分配数学。对一个变量进行随机赋值,并在返回前执行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);

}

如果它已经返回到if块上,则不会进入if块。