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

时间:2016-12-17 19:58:39

标签: javascript ajax function var

Okey所以我有两个AJAX调用,在其中我有两个我想要访问的变量,所以我可以用它们做一些数学并得到它们之间的区别!

我的代码:

#include <iostream>
#include <gtkmm-3.0/gtkmm.h>

struct DragButton : Gtk::CheckButton{
    DragButton(){
        this->signal_drag_begin().connect([](const Glib::RefPtr<Gdk::DragContext>& ctx){
            ctx->set_icon();
        });
        this->drag_source_set({Gtk::TargetEntry("testdata")});
        this->drag_dest_set({Gtk::TargetEntry("testdata")});

        this->signal_drag_data_get().connect(
            [this](const Glib::RefPtr<Gdk::DragContext>&,Gtk::SelectionData& s,guint,guint ){
                std::cout << "sending data." << std::endl;
            }
        );
        this->signal_drag_data_received().connect(
            [](const Glib::RefPtr<Gdk::DragContext>& c,int,int,const Gtk::SelectionData&,guint,guint time){
                std::cout << "receiving data" << std::endl;
                c->drop_finish(true,time);
            }
        );
    }
};

int main(){
    auto app = Gtk::Application::create("test");
    auto settings = Gtk::Settings::get_default();
    settings->set_property<Glib::ustring>("gtk-font-name","Sans 10");

    Gtk::Window window;
    window.set_default_size(100,50);
    Gtk::Box box;

    for(int i = 0; i < 3; i++){
        box.pack_end(*Gtk::manage(new DragButton));
    }

    window.add(box);
    window.show_all();

    app->run(window);
}

我想找到&#39; sugString&#39;之间的区别。和&#34; htmlString&#34;然后我想把它再次放入我的html代码中,就像我使用&#39; sugString&#39;和&#39; htmlString&#39;。关于我如何做到这一点,任何人都得到了一个很好的答案?谢谢你的时间! :)

我得到了这个解决方案,但后来我得到了这个错误:无法读取属性&#39;皮肤:火红的骷髅脸头巾&#39;未定义的

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

1 个答案:

答案 0 :(得分:1)

仅仅为了让你的变量在同一个上下文中可用,你可以在函数之外声明它们 - 同时在你的函数中保持它们的分配。解决方案的简单概述是:

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