带有 if-else 的功能无法正常工作

Function with if-else doesn't work properly

本文关键字:常工作 工作 if-else 功能 带有      更新时间:2023-09-26

我做了一个函数,如果一个变量不大于或等于另一个变量,它应该禁用一个按钮。此函数在 setInterval() 上每秒运行一次,并且要比较的第一个变量在 setInterval() 上也递增 1。但是,该函数(evitarNegs())无法正常工作,并且按钮始终处于禁用状态。抱歉,部分代码是西班牙语。

Javascript:

var GmB = {cantidad: 0, perSec: 1};
function Upgrade (pb, ps) {
    this.precioBase = pb;
    this.perSec = ps;
    this.cantidad = 0;
    this.precio = pb;
}
Upgrade.prototype.comprar = function() {
    GmB.cantidad = GmB.cantidad - this.precio;
    GmB.perSec = GmB.perSec + this.perSec;
    this.cantidad++;
    document.getElementById("gmb").innerHTML = GmB.cantidad;
    this.precio = Math.ceil(this.precioBase*Math.pow(1.15, this.cantidad));
    evitarNegs();
};
function loop() {
    GmB.cantidad = GmB.cantidad + GmB.perSec;
    document.getElementById("gmb").innerHTML = GmB.cantidad;
    evitarNegs();
}
var upg = new Upgrade(10, 1);
var boton1 = document.getElementById("boton1");
boton1.disabled = true;
window.setInterval(loop, 1000);
//Problematic function
function evitarNegs() {
    if (!(GmB >= upg.precio)) {
        boton1.disabled = true;
    }else {
        boton1.disabled = false;
    }
}
boton1.onclick = function() {
    upg.comprar();
};

.HTML:

<html>
    <head>
        <title>Gummy Bears</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width">
    </head>
    <body>
        <p id="gmb">0</p>
        <button id="boton1" type="button">Upgrade 1</button>
        <script src="main.js"></script>
    </body>
</html>

您正在将GmBupg.precio进行比较,但GmB是一个对象。所以你想要

function evitarNegs() {
    if (!(GmB.cantidad >= upg.precio)) {
        boton1.disabled = true;
    } else {
        boton1.disabled = false;
    }
}

但是,这可以写得更容易

function evitarNegs() {
    boton1.disabled = GmB.cantidad < upg.precio;
}

小提琴:http://jsfiddle.net/4rRmp/

您似乎正在将对象与 GmB >= upg.precio 中的整数进行比较。您可能必须将其替换为 GmB.cantidad >= upg.precio .