[英]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.
我将它传递给另一个 function 然后记录它。 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.
第一次我记录整个 object 并获得所需的 output,但第二次我尝试在 object 中记录数组时,我得到一个空数组。 (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:回应1:
{…}
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:回应2:
[]
length: 0
<prototype>: Array []
data from console.log(data["zt"])来自 console.log 的数据(数据 [“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从上面的响应可以看出, iH是一个长度为 9 的数组,但是当我记录它时,我得到一个空数组
It might be an async problem, where the data object only gets filled after you console.log it.这可能是一个异步问题,其中数据 object 仅在您 console.log 后才被填充。 Try logging
console.log({...data})
or console.log(JSON.stringify(data))
to make sure the data is there when f2 is called.尝试记录
console.log({...data})
或console.log(JSON.stringify(data))
以确保在调用 f2 时数据存在。
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.背景:当您使用console.log(data),然后在控制台中查看它时,它将包含即使在console.log 调用之后发生的更改。 This is because data is an object, and you are just logging the reference to the object, not the value of the object itself.
这是因为数据是 object,而您只是记录对 object 的引用,而不是 object 本身的值。 Here's an example: https://jsfiddle.net/michaschwab/f61tdue5/3/
这是一个例子: https://jsfiddle.net/michaschwab/f61tdue5/3/
try this way console.log(data[zt]) console.log(data[iH])
试试这种方式
console.log(data[zt]) console.log(data[iH])
or或者
console.log(data[zt],data[iH])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.