繁体   English   中英

Javascript全局变量及其引用及其部分

[英]Javascript global variables and references to them and their parts

我正在编写一些摘要,以了解有关将Javascript与API结合使用的更多信息,并且偶然发现了另一个我自己无法解决的问题。 我有一个从API读取的全局变量(对象?)“硬币”,及其数据字段“符号”。 我可以在部分代码中使用“符号”来引用其中保存的数据,而不会出现任何错误。 在以后的代码中,我再次使用它,并且尽管定义为使用它返回的值都已定义,并且达到了我的期望,但仍然收到未定义的错误。 在讨论过程中,也许有人可以告诉我为什么我要给全局变量赋值(在所有函数的外部声明),但是变量在调用时是“未定义的”。 要查看实际效果,请访问www.mattox.space/XCR并打开开发工具。

            /*

    FLOW:
    get ALL coins, store NAME and SYMBOL into an object.
    loop over the names object comparing to $SYMBOL text from form, return the NAME when found.
    hit the API again, with the $NAME added to the URL.
    create a table row.
    insert data from second API hit, into table row
    SOMEWHERE in there, do the USD conversion from BTC.
    */

    //var name = getName();
    var bitcoinValue = 0;
    var coins = new Array;
    var form = ""; // Value pulled from the form
    var symbol = ""; // "id" on the table
    var id = ""; // value pulled from the table at coins[i].id matched to coins[i].symbol

    var formSym = "";
    var formUSD = 0;
    var formBTC = 0;
    var form24h = 0;

    function run() {
      getFormData();
      allTheCoins("https://api.coinmarketcap.com/v1/ticker/");
      testGlobal();
    }


    function testGlobal() {
      console.log("These are hopefully the values of the global variables");
      console.log(formSym + " testGlobal");
      console.log(formUSD + " testGlobal");
      console.log(formBTC + " testGlobal");
      console.log(form24h + " testGlobal");
    }

    function getFormData(){ //This function works GREAT!
      form = document.getElementById("symbol").value //THIS WORKS
      form = form.toUpperCase(); //THIS WORKS
    }

    function allTheCoins(URL) {
      var tickerRequest = new XMLHttpRequest();
      tickerRequest.open('GET', URL);
      tickerRequest.send();
      tickerRequest.onload = function() {
        if (tickerRequest.status >= 200 && tickerRequest.status < 400) {
          var input = JSON.parse(tickerRequest.responseText);
          for(var i in input)
          coins.push(input[i]);
          testFunction(coins);
        }
        else {
          console.log("We connected to the server, but it returned an error.");
        }
        console.log(formSym + " allTheCoins!"); // NOPE NOPE NOPE
        console.log(formUSD) + " allTheCoins!"; // NOPE NOPE NOPE
        console.log(formBTC + " allTheCoins!"); // NOPE NOPE NOPE
        console.log(form24h + " allTheCoins!"); // NOPE NOPE NOPE
      }
    }

    function testFunction(coins) {
      for (var i = 0; i < coins.length; i++) {

        if (coins[i].symbol == form) { // But right here, I get an error.
          formSym = coins[i].name;
          formUSD = coins[i].price_usd;
          formBTC = coins[i].price_btc;
          form24h = coins[i].percent_change_24h;
          console.log(formSym + " testFunction");
          console.log(formUSD + " testFunction");
          console.log(formBTC + " testFunction");
          console.log(form24h + " testFunction");
          //DO EVERYTHING RIGHT HERE! On second thought, no, this needs fixed.
        }
        else if (i > coins.length) {
          formSym = "Error";
          formUSD = 0;
          formBTC = 0;
          form24h = 0;
        }
      }
    }
    /*

    if (24h >= 0) {
    colorRED
    }
    else {
    colorGreen
    }

    */

这是一种可能会启发您的方法。 其基于设置了标头和方法的httpRequest承诺。

    let allTheCoins = obj => {
    return new Promise((resolve, reject) => {
        let xhr = new XMLHttpRequest();
        xhr.open(obj.method || obj.method, obj.url);
        if (obj.headers) {
            Object.keys(obj.headers).forEach(key => {
                xhr.setRequestHeader(key, obj.headers[key]);
            });
        }
        xhr.onload = () => {
            if (xhr.status >= 200 && xhr.status < 300) {
                resolve(xhr.response);
            } else {
                reject(xhr.statusText);
            }
        };
        xhr.onerror = () => reject(xhr.statusText);
        xhr.send(obj.body);
    });
};

allTheCoins({
    url: "https://api.coinmarketcap.com/v1/ticker/",
    method: "GET",
    headers: {"Accept-Encoding": "gzip"}
})
        .then(data => {
            ParseCoins(data);
        })
        .catch(error => {
            console.log("We connected to the server, but it returned an error.");
        });

function ParseCoins(data) {
    const coins = JSON.parse(data);
    const form = getFormVal();/*retrieve form val*/
    const id = getTableId(); /*retrieve table id*/
    const bitcoinValue = getBitcoinVal();/*retrieve bitcoin Value*/
    const final_result = [];
    for (let i = 0, len = coins[0].length; i < len; i++) {
        const coin = coins[0][i];
        for (let ii in coin) {
            if (coin.hasOwnProperty(ii)) {
                if (coin[ii].symbol == form) {
                    let element = {
                        formSym: coin[ii].name,
                        formUSD: coin[ii].price_usd,
                        formBTC: coin[ii].price_btc,
                        form24h: coin[ii].percent_change_24h
                    };
                    final_result.push(element);
                }
            }
        }
    }
    coontinueElseWhere(final_result);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM