简体   繁体   中英

Why does the object (containing an array) passed to second function, give an empty array when I try to access its array?

I am getting a response data . I pass it to another function and then log it. The first time I log the entire object and get the desired output, but the second time I try to log the array inside that object, I get an empty array. (I have cross checked that array is not empty).

const f1 = () => {
  window.gapi.load('analytics', async function() {
    window.gapi.analytics.auth.authorize({
      'serverAuth': {
        'access_token': access_token
      }
    });
    const data = await new window.gapi.analytics.ViewSelector({
            container: 'view-selector-container'

    });
    data.execute();
    f2(data);
  });

}

const f2 = async function (data){
  console.log(data);
  console.log(data["zt"]["iH"]);
}

response1:

      {…}
​
Jd: Object { Lb: false, Zh: 1, Sw: 0, … }
​
Rb: Object { container: "view-selector-container" }
​
TM: Object { Lb: false, gx: false, Va: true, … }
​
hH: Object { Lb: false, gx: false, Va: true, … }
​
ids: "ga:176819049"
​
mP: Object { Lb: false, gx: false, Va: true, … }
​
zt: Object { iH: (9) […], gH: {…}, SM: {…}, … }

response2:

  []
​
length: 0
​
<prototype>: Array []

data from console.log(data["zt"])

​
zt: {
​​
SM: Object { "UA-xx2": {…}, "UA-xx-1": {…}, "UA-xx-1": {…}, … }
​​
gH: Object { 34199158: {…}, 44335927: {…}, 64056475: {…}, … }
​​
iH: Array(9) [ {…}, {…}, {…}, … ]
​​
r3: Object { 63179797: {…}, 77047380: {…}, 91559901: {…}, … }
​​
<prototype>: Object { fetch: fetch(), … }
​
<prototype>: Object { constructor: RE(a), execute: execute(), gt: gt(), … }
    }

as can be seen from the response above, iH is an array of length 9, but when I log it I get an empty array

It might be an async problem, where the data object only gets filled after you console.log it. Try logging console.log({...data}) or console.log(JSON.stringify(data)) to make sure the data is there when f2 is called.

Background: When you console.log(data), and then look at it in the console, then it will contain changes that occur even after the console.log call. This is because data is an object, and you are just logging the reference to the object, not the value of the object itself. Here's an example: https://jsfiddle.net/michaschwab/f61tdue5/3/

try this way console.log(data[zt]) console.log(data[iH])

or

console.log(data[zt],data[iH])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM