将变量传递给不同的函数

时间:2015-07-17 19:52:27

标签: 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 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
       });
   });

3 个答案:

答案 0 :(得分:1)

您可以执行以下操作。

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]);
            });

        });
    });

答案 1 :(得分:0)

您需要第二次取消声明total_count

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

更改为

total_count = data.rows[0].count;

答案 2 :(得分:0)

您已经在

之外宣布了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
    });

由于范围更改,该值将分配给内部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
    });