Javascript 将变量传递到不同的函数中

Javascript 将变量传递到不同的函数中,javascript,jquery,ajax,json,Javascript,Jquery,Ajax,Json,我在获取我在别处计算的变量的值以在另一个函数中工作时遇到问题。我知道我遗漏了一些明显的东西,但不确定是什么。我的代码是这样的: var total_count; function getDistances() { $.getJSON('https://something.com', function(data){ var total_count = data.rows[0].count; //this is the correct value for tot

我在获取我在别处计算的变量的值以在另一个函数中工作时遇到问题。我知道我遗漏了一些明显的东西,但不确定是什么。我的代码是这样的:

var total_count;    
    function getDistances() {
    $.getJSON('https://something.com', function(data){
       var total_count = data.rows[0].count; //this is the correct value for total_count
    });
    $.getJSON('https://anotherthing.com', function(data){
      d1_1 = [];
      var limit = 4;

       $.each(data.rows, function(index, item){
         if(index > limit) 
           return false;
         console.log(total_count); //This is undefined  
         d1_1.push([Math.round((item.count/total_count*100)*100)/100,index]);
         //because total_count is undefined here, I get NaNs
       });
   });

您需要第二次取消申报
total_count

var total_count = data.rows[0].count;//var total_count has been declared
改为

total_count = data.rows[0].count;

您已声明总数超出

function getDistances() {
$.getJSON('https://something.com', function(data){
              var total_count = data.rows[0].count; //this is the correct value for total_count
    });
由于作用域的变化,该值被分配给内部的total_count,而不是外部的total_count

因此,总而言之,代码应该是:

var total_count;    
function getDistances() {
$.getJSON('https://something.com', function(data){
              total_count = data.rows[0].count; //this is the correct value for total_count
    });  

你可以像下面这样做

function getDistances() {
    $.getJSON('https://something.com', function (data1) {
        var total_count = data1.rows[0].count;
        $.getJSON('https://anotherthing.com', function (data) {
            d1_1 = [];
            var limit = 4;

            $.each(data.rows, function (index, item) {
                if (index > limit) return false;
                console.log(total_count);
                d1_1.push([Math.round((item.count / total_count * 100) * 100) / 100, index]);
            });

        });
    });

我知道这很简单。这就成功了。如果允许的话,我会接受的。谢谢