当我试图在.each函数之外使用它时,变量变成Nan

Variable becomes Nan when i try to use it outside of the .each function

本文关键字:变量 Nan each 函数      更新时间:2023-09-26

我正在从外部源抓取JSON obj。看起来是这样的:

{"total":16231642,"totalamount":437442282.55}

我将其设置为全局变量,在每个函数中设置它,然后尝试在它之外检索它,如下所示。但是我得到一个Nan作为值。这个值肯定是在函数中设置的,所以我不完全确定为什么会发生这种情况。

任何帮助都是感激的!

$( document ).ready(function() {
    var todaystart;
    //Get vals from JSON txt
        $.getJSON( "proxy.php", function( data ) {
        $.each(data, function (key, val) {
            if (key == 'totalamount')
            {
                var todaystart = val; //was using parseFloat before to ensure that the datatype was correct, in case anybody answers that.
                //alert(todaystart);                
            }
        });

        });

            //Total Earned
            var avgvol = 18556;
            var price = 26.95;
            var avg = avgvol * price;
            alert(todaystart);
            var avgpls = todaystart + avg;
            var numAnim = new countUp("totalmon", todaystart, avgpls, 0, 86400);
                numAnim.start();
        //Sess Earned       
            remavgpls = avgpls - todaystart;    
            var nu2Anim = new countUp("sessmon", 0, remavgpls, 0, 86400);
                nu2Anim.start();
        //Sess Time     
            var nu3Anim = new countUp("minmon", 0, 86400, 0, 864000);
                nu3Anim.start();
    });

删除if语句var todaystart;中的var关键字

 if (key == 'totalamount')
            {
                todaystart = val; //was using parseFloat before to ensure that the datatype was correct, in case anybody answers that.
                //alert(todaystart);                
            }

完整的代码将是

$(document).ready(function () {
    var todaystart;
    //Get vals from JSON txt
    $.getJSON("proxy.php", function (data) {
        $.each(data, function (key, val) {
            if (key == 'totalamount') {
                todaystart = val; //was using parseFloat before to ensure that the datatype was correct, in case anybody answers that.
                //alert(todaystart);                
            }
        });
        calcualtion();

    });
});
function calcualtion() {
    var avgvol = 18556;
    var price = 26.95;
    var avg = avgvol * price;
    alert(todaystart);
    var avgpls = todaystart + avg;
    var numAnim = new countUp("totalmon", todaystart, avgpls, 0, 86400);
    numAnim.start();
    //Sess Earned       
    remavgpls = avgpls - todaystart;
    var nu2Anim = new countUp("sessmon", 0, remavgpls, 0, 86400);
    nu2Anim.start();
    //Sess Time     
    var nu3Anim = new countUp("minmon", 0, 86400, 0, 864000);
    nu3Anim.start();
}

注意:将计算代码移动到getJSON方法中,因为getJSON是异步函数

每次循环打开时都在声明变量'todaystart',这应该避免。永远不要在循环中创建变量,而是将其作为全局变量,以提高客户端性能。