这是我的JS:

var money = 4;
var thirst = 50;
function satisfy(what,how,price,sBar){
    if(price<=money){
        what=what+how;
        money=money-price;
        updateBar(sBar,what);
        updateMoney();
    } else {
        log.unshift("D"+day+" "+hour+":"+minute+" - Poor hobo, you don't have enough money for that. <br>");
        updateLog();
    };
};


这是在我的HTML

<a onClick="satisfy(thirst,30,0.84,'#thirst')";>buy</a>


单击后,问题是thirst的全局变量没有更新,但是money全局变量得到了更新。我该如何修复它以也更新thirst全局变量?

非常感谢你。

最佳答案

这是因为JavaScript数字是通过值而不是通过引用传递的,这意味着创建并修改了thirst的副本。为什么不返回值呢?

HTML:

<a id="buy-link">buy</a>


JavaScript:

var money = 4;
var thirst = 50;

function satisfy(what, how, price, sBar) {
    if (price <= money){
        what += how;
        money -= price;
        updateBar(sBar,what);
        updateMoney();
    } else {
        log.unshift("D" + day + " " + hour + ":" + minute + " - Poor hobo, you don't have enough money for that. <br>");
        updateLog();
    }

    return what;
}

var buyLink = document.getElementById("buy-link");
buyLink.addEventListener("click", function() {
    thirst = satisfy(thirst, 30, 0.84, '#thirst')
}, false);


我还删除了一些不需要的分号,将事件处理程序转换为使用标准的addEventListener函数,并稍微清理了一下代码。

10-08 08:02
查看更多