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

时间:2014-07-22 05:42:45

标签: javascript jquery json nan

我从外部源抓取JSON obj。看起来如此:

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

我将它设置为全局var,在每个函数中设置它,然后尝试在它之外检索它。但我得到了一个N​​an作为价值。该值是在函数中设置的,因此我不完全确定为什么会发生这种情况。

感谢任何帮助!

$( 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();
    });

2 个答案:

答案 0 :(得分:2)

删除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方法中移动计算代码bcoz getJSON是异步函数

答案 1 :(得分:0)

您正在重新宣布变量' todaystart'每次循环打开时都应该避免。永远不要在内部循环中创建变量,而是将其作为全局变量,以提高客户端性能。