当我尝试在.each函数之外使用它时,变量变为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(); }); 

如果语句var todaystart;删除var关键字var todaystart;

  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是异步函数

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