İsa C.
İsa C.

Reputation: 329

Why can't I detect unknown value in Array array?

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
                }

Upvotes: 0

Views: 165

Answers (3)

siniradam
siniradam

Reputation: 2929

If your error happening on a line you can't expect to correct an error after executing that line. You need to fix that specific line.

So you may choose to define a static alternate value for that variable, or you should define action in the absence of that value.

This prevents error throw, but undefined will be assigned to total.

total = tradeCoinHistoryArray[i]?.total;

This assigns an alternate value to your total.

total = (tradeCoinHistoryArray[i]?.total) ? tradeCoinHistoryArray[i].total : 0;

If you need to stick es5

total = (tradeCoinHistoryArray[i].total !== undefined) ? tradeCoinHistoryArray[i].total:0

Upvotes: 1

Yadnesh Khode
Yadnesh Khode

Reputation: 14

You can use:

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

Upvotes: -1

Jagrut Sharma
Jagrut Sharma

Reputation: 4754

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;
}

Upvotes: 1

Related Questions