0

[enter image description here][1]

I print a variable by console.log(TotalTime) and this is the result. It looks like an array but it's not. There are some other console.log commands: console.log(typeof TotalTime) => Object console.log(TotalTime[0]) => undefine i need to access the element shown in the picture but i couldn't. How can I get it? I need to calculate the sum of it. Here is my code:

getLightTimeUsing = async () => {
    const url = "";
    const devices = await axiosClient.get(url);
    var totalTime = [];

    devices.forEach(async (device) => {
      // console.log(device);
      if (device.description === "light") {
        let lightdevices = await this.getFeedData(device.key);
        lightdevices = [...lightdevices.reverse()];
        // console.log(lightdevices.length);
        lightdevices.forEach((ldevice, index, arr) => {
          if (index % 2 !== 1) {
            totalTime.push(
              Date.parse(arr[index + 1].created_at) -
                Date.parse(ldevice.created_at)
            );
          }
        });
      }
    });
    console.log(totalTime[0]) //=> undefine
    console.log(typeof totalTime) //=> object
    return totalTime;
  };
  • 2
    "// use Array.isArray or Object.prototype.toString.call // to differentiate regular objects from arrays typeof [1, 2, 4] === 'object';" https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof – bhspencer Apr 26 '22 at 16:01
  • 1
    You have an array. Not sure why console.log(TotalTime[0]) is not working. Post a compete example. I imagine there is something else going on that is not shown in your question. – bhspencer Apr 26 '22 at 16:03
  • I cann't understand the scope variable in js they're so confusing – luân đặng Apr 26 '22 at 16:53
  • Use `for … of` instead of `forEach` (See linked duplicate for more details). And `typeof` of an array is specified to be `object`. – t.niese Apr 26 '22 at 17:07

0 Answers0