如何使用来自不同函数的变量进行数学运算

How to do math with variables from different functions

好的,所以我得到了两个 AJAX 调用,在它们里面我有两个我想访问的变量,所以我可以用它们做一些数学运算并得到它们之间的区别!

我的代码:

var flamingSkull = document.getElementById("flaming-skull");
var flamingSkullq = document.getElementById("flaming-skullq");
var flamingSkullSug = document.getElementById("flaming-skullsug");

  var ourRequest = new XMLHttpRequest();
    ourRequest.open('GET', 'https://api.opskins.com/IPricing/GetAllLowestListPrices/v1/?appid=433850');
    ourRequest.onload = function() {
      var ourData = JSON.parse(ourRequest.responseText);
      renderFlamingSkull(ourData);
};

   ourRequest.send();


var ourRequest2 = new XMLHttpRequest();
  ourRequest2.open('GET', 'https://api.opskins.com/IPricing/GetPriceList/v1/?appid=433850');
  ourRequest2.onload = function() {
     var ourData2 = JSON.parse(ourRequest2.responseText);
     renderFlamingSkullSug(ourData2);
};

   ourRequest2.send();



function renderFlamingSkullSug(data) {

   var sugString = data.response[ 'Skin: Flaming Skull Face Bandana' ][today].price / 100;

   flamingSkullSug.insertAdjacentHTML('beforeend', "$" + sugString);
}

function renderFlamingSkull(data) {

   var htmlString = data.response[ 'Skin: Flaming Skull Face Bandana' ].price / 100;
   var quantityString = data.response[ 'Skin: Flaming Skull Face Bandana' ].quantity;


   flamingSkull.insertAdjacentHTML('afterbegin', "$" + htmlString);
   flamingSkullq.insertAdjacentHTML('beforeend', "<p>(" + quantityString + ")</p>");
}

我想找到 'sugString' 和 "htmlString" 之间的区别,然后我想再次将它放入我的 html 代码中,就像我对 'sugString' 和 'htmlString'。有人对我如何做到这一点有很好的回答吗?谢谢你的时间! :)

我得到了这个解决方案,但后来我得到了这个错误:无法读取未定义的 属性 'Skin: Flaming Skull Face Bandana'

var flamingSkull = document.getElementById("flaming-skull");
var flamingSkullq = document.getElementById("flaming-skullq");
var flamingSkullSug = document.getElementById("flaming-skullsug");
var lowestPriceUrl = 'https://api.opskins.com/IPricing/GetAllLowestListPrices/v1/?appid=433850';
var priceListUrl = 'https://api.opskins.com/IPricing/GetPriceList/v1/?appid=433850';

function makeRequest (method, url, done) {
var xhr = new XMLHttpRequest();
xhr.open(method, url);
xhr.onload = function () {
done(null, xhr.response);
};
xhr.onerror = function () {
done(xhr.response);
};
xhr.send();
}


makeRequest('GET', lowestPriceUrl, function (err, res) {
   if (err) { throw err; }

makeRequest('GET', priceListUrl, function (err, res2) {
   if (err) { throw err; }

var sugString = res.response[ 'Skin: Flaming Skull Face Bandana' ][today].price / 100;
   var htmlString = res2.response[ 'Skin: Flaming Skull Face Bandana' ].price / 100;
   var quantityString = res2.response[ 'Skin: Flaming Skull Face Bandana' ].quantity;

flamingSkullSug.insertAdjacentHTML('beforeend', "$" + sugString);
flamingSkull.insertAdjacentHTML('afterbegin', "$" + htmlString);
flamingSkullq.insertAdjacentHTML('beforeend', "<p>(" + quantityString + ")</p>");

// Complete division
// ==================
// var division = Math.round(sugString/htmlString)
  });
 });

仅仅为了让您的变量在同一上下文中可用,您可以在您的函数之外声明它们 - 同时在您的函数中继续为它们赋值。解决方案的简单概述是:

var sugString;
var htmlString;
var quantityString;

function renderFlamingSkullSug(data) {

   sugString = ...

   ...
}

function renderFlamingSkull(data) {

   htmlString = ...
   quantityString = ...
    ...
}

// Execute your functions

// Then do some maths

然而,在你的情况下,你的函数是异步调用的,所以你需要放置一些额外的机制来确保你的回调在对它们分配给的变量进行一些数学运算之前实际执行。

在您的特定情况下,一种更简单的方法可能是将您的数学逻辑包含在回调函数中 - 并使用标志机制来决定您是否准备好执行它。

var sugString;
var htmlString;
var quantityString;
var firstCallbackExecuted = false;

function renderFlamingSkullSug(data) {

   sugString = ...
   if (firstCallbackExecuted) {
       doSomeMathAndDomManipulation()
   }
   firstCallbackExecuted = true;
   ...
}

function renderFlamingSkull(data) {

   htmlString = ...
   quantityString = ...
   if (firstCallbackExecuted) {
       doSomeMathAndDomManipulation()
   }
   firstCallbackExecuted = true;
    ...
}

// Execute functions asynchronously

function doSomeMathAndDomManipulation(){...};

里面有一点重复,你可以分解一点,但这是一般的想法。

编辑:填空的完整解决方案如下。正如我在评论中指出的那样,您仍然需要解决您的代码可能涉及的任何其他挥之不去的问题。我只是用你提供的代码填补了一般解决方案大纲的空白。

var sugString;
var htmlString;
var quantityString;
var firstCallbackExecuted = false;

var flamingSkull = document.getElementById("flaming-skull");
var flamingSkullq = document.getElementById("flaming-skullq");
var flamingSkullSug = document.getElementById("flaming-skullsug");

var ourRequest = new XMLHttpRequest();
    ourRequest.open('GET', 'https://api.opskins.com/IPricing/GetAllLowestListPrices/v1/?appid=433850');
    ourRequest.onload = function() {
        if(this.status === 200) {
            var ourData = JSON.parse(ourRequest.responseText);
            renderFlamingSkull(ourData);
        } else {
            console.log('Status is not 200');
        }
};

var ourRequest2 = new XMLHttpRequest();
    ourRequest2.open('GET', 'https://api.opskins.com/IPricing/GetPriceList/v1/?appid=433850');
    ourRequest2.onload = function() {
        if(this.status === 200) {
            var ourData2 = JSON.parse(ourRequest2.responseText);
            renderFlamingSkullSug(ourData2);
        } else {
            console.log('Status is not 200');
        }
};

ourRequest.send();
ourRequest2.send();

function renderFlamingSkullSug(data) {

   var MostRecentDateAvailable = getMostRecentDate(data.response[ 'Skin: Flaming Skull Face Bandana' ]);

   sugString = data.response[ 'Skin: Flaming Skull Face Bandana' ][MostRecentDateAvailable].price / 100;

   manageMath();

   flamingSkullSug.insertAdjacentHTML('beforeend', "$" + sugString);
}

function renderFlamingSkull(data) {

   htmlString = data.response[ 'Skin: Flaming Skull Face Bandana' ].price / 100;
   quantityString = data.response[ 'Skin: Flaming Skull Face Bandana' ].quantity;

   manageMath();

   flamingSkull.insertAdjacentHTML('afterbegin', "$" + htmlString);
   flamingSkullq.insertAdjacentHTML('beforeend', "<p>(" + quantityString + ")</p>");
}

function doSomeMathAndDomManipulation(){
    // This is where you put you math and dom logic
    // relying on the sugString, htmlString, and quantityString variables
}

function manageMath(){
    if (firstCallbackExecuted) {
       doSomeMathAndDomManipulation()
    }
    firstCallbackExecuted = true;
}

// Method for converting date object to "yyyy-mm-dd" string format
Date.prototype.custoFormat = function(){
  var day = format2Digits(date.getDate());
  var month = format2Digits(date.getMonth() + 1);
  var year = date.getFullYear();
  return year + '-' + month + '-' + day;
};        

// Helper function
function format2Digits(n){
  return n<10? '0'+n:''+n;
}

function getMostRecentDate(obj){
    var date = new Date();
    var tryNb = 10;

    while(!obj[date.custoFormat()]){
      if(tryNb === 10) {
        console.log("Too many tries");
        return false;
      }
      date.setDate(date.getDate() - 1);
      tryNb++;
    }

    return date.custoFormat();
}