Home > Software engineering >  Why can't I detect unknown value in Array array?
Why can't I detect unknown value in Array array?

Time:10-03

I need to pull data from a site in json format.

I am successfully pulling this data and adding it to the array. I then need to use the data in this string with a for loop.

But sometimes I get the following error. I haven't been able to figure out the reason for this. I'm sending too many requests. (more than 500 in 5 seconds) The code gives an error when adding the total value as "undefined" to the Array array or not. I couldn't solve it.

At least I tried to keep the code running if the total value contains "undefined" but still failed. I keep getting errors.

I would be very grateful for any help. Sorry for my bad english.

error:

var totalArr = tradeCoinHistoryArray[i].total;         
TypeError: Cannot read property 'total' of undefined

code:

request(TRADE_HISTORY_URL   coin, function (error, response, body) {
      if (!error && response.statusCode == 200) {
          var importedJSON = JSON.parse(body);
  
          tradeCoinHistoryArray = importedJSON.data;   

              for (var i = tradeCoinHistoryArray.length - TRADE_LAST_TRADE_COUNT; i < tradeCoinHistoryArray.length; i  ) {

                //error line
                total = tradeCoinHistoryArray[i].total;
                //error line


                if(total == undefined){
                  //console.log("continue if total is undefined";
                  return
                }

CodePudding user response:

The error is due to tradeCoinHistoryArray[i] object not being defined.

You can add a check:

if (tradeCoinHistoryArray[i] && tradeCoinHistoryArray[i].hasOwnProperty('total')) {
     total = tradeCoinHistoryArray[i].total;
}

CodePudding user response:

you can write if(tradeCoinHistoryArray[i]){total = tradeCoinHistoryArray[i].total }

  • Related