2017-07-07 7 views
0

JavaScriptでJavascriptを使用する方法の詳細については少ししか書いていませんが、私自身は理解できない別の問題に遭遇しました。私は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

関連する問題