2017-07-07 44 views
0

我正在寫小片段來了解更多關於如何將Javascript用於API的問題,並且偶然發現了另一個我自己無法弄清楚的問題。我有一個全局變量(對象?)「硬幣」,從API中讀入,以及它的'數據字段'符號「。我可以使用「符號」在部分代碼中引用保存在那裏的數據,而不會出現任何錯誤。在後面的代碼中,我再次使用它,並且我得到一個關於它未定義的錯誤,儘管使用它返回的值都是定義的,而且我期望的。當我們處理它時,也許有人可以告訴我爲什麼給全局變量賦值(在所有函數之外聲明),但調用時的變量是「未定義的」。要看到它的行動,請訪問www.mattox.space/XCR並打開開發工具。Javascript全局變量以及對它們及其部分的引用

  /* 

    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 
    } 

    */ 
+1

'coins [i]'''undefined'因爲您迭代了數組的末尾。當您嘗試訪問'coins [i] .symbol'時會導致錯誤。將'testFunction'中的循環條件從'i <(coins.length + 1)'改變爲'i Paulpro

+2

這裏有很多代碼。你能簡化它到與你的問題相關的部分,並刪除所有註釋掉的代碼嗎? – Barmar

+0

我修正了上面的代碼,使其更具可讀性,但我將刪除此帖子,除非有異議。刪除那個「+ 1」有幫助,但最大的問題是,我試圖調用的值並非來自xhr的「準備好」。我需要學習回調或承諾(不能完全包裝我的頭腦,謝謝你們不只是簡單地投票,而是繼續前進) – dmattox10

回答

1

這是一個可能的方式,你可以從中獲得靈感。它基於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); 
} 
+0

我會在回家後測試這段代碼,並希望將其標記爲回答! – dmattox10

+0

根據API響應(對象或數組?)可能會產生一個小故障。推入硬幣陣列可能會重新... – cpugourou

+0

它返回一個數組中的一個對象,以及956個對象 – dmattox10