2

我得到 Uncaught TypeError: "Cannot read property '0' of undefined" 错误。我就是想不通这个问题。

尽管程序运行良好,但我得到了所需的输出。但是错误...

控制台截图 控制台截图/resp 对象

$(window).bind("load", function() {

var ws = new WebSocket("wss://www.bitmex.com/realtime?subscribe=trade:XBTUSD");

ws.onopen = function(){
  ws.send(JSON.stringify({"trade":"XBTUSD"}))
};

ws.onmessage = function (msg){
    var resp = JSON.parse(msg.data);
    console.log(resp);  

    var price = resp['data'][0].price; // can not read property 0 of undefined :/

    console.log('Price is : ' + price);


};

});
4

1 回答 1

2

检查是否resp/resp.data为空。如果resp/resp.data为 null,则 index 处没有任何内容0

   ws.onmessage = function (msg){
       var resp = JSON.parse(msg.data);
       console.log('Data : ' + data);  
       console.log('resp: ' + resp);  
       var price;
       if(resp && resp.data){
          price = resp.data[0].price; // can not read property 0 of undefined :/
       }

       console.log('Price is : ' + price);

      //document.getElementById('btcPrice').value = price;

   };
于 2018-10-03T06:58:11.337 回答