JavaScript-console.log显示列表,在访问时给出未定义的
上下文 在我当前的应用程序(chrome扩展)中,所有网站访问都会被记录并添加到Firebase中,在Firebase中使用一个函数可以获取当天访问的网站的对象列表 问题 现在从这些对象中,我计划将唯一的名称提取到一个列表中,这带来了一点问题,因为保存这些对象的列表似乎并不“存在”。当I console.log退出时,它显示为>[]!'下面的值是刚才计算的,然后显示这些项目的值 但是,当我尝试使用索引访问它们时,它显示为未定义。即使在运行调试器时,出于某种原因,它似乎给出了一个空列表,但正如前面提到的,列表的普通console.log给出了预期的结果 示例代码JavaScript-console.log显示列表,在访问时给出未定义的,javascript,firebase,google-chrome-extension,firebase-realtime-database,undefined,Javascript,Firebase,Google Chrome Extension,Firebase Realtime Database,Undefined,上下文 在我当前的应用程序(chrome扩展)中,所有网站访问都会被记录并添加到Firebase中,在Firebase中使用一个函数可以获取当天访问的网站的对象列表 问题 现在从这些对象中,我计划将唯一的名称提取到一个列表中,这带来了一点问题,因为保存这些对象的列表似乎并不“存在”。当I console.log退出时,它显示为>[]!'下面的值是刚才计算的,然后显示这些项目的值 但是,当我尝试使用索引访问它们时,它显示为未定义。即使在运行调试器时,出于某种原因,它似乎给出了一个空列表,但正如前面
function Master() {
firebase.initializeApp(config);
let that = this;
this.http_usage = this.get_http();
this.https_usage = this.get_https();
this.todays_usage = this.get_today_sites();
this.site_names = [];
console.log(this.todays_usage);
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
console.log(request.message);
if (request.message === "hello") {
sendResponse({farewell: [that.http_usage.length, that.https_usage.length]});
}
});
this.init();
}
get_today_sites: function () {
let content = [];
let start = new Date();
start.setHours(0, 0, 0, 0);
start = start.getTime();
let end = new Date();
end.setHours(23, 59, 59, 999);
end = end.getTime();
let ref = firebase.database().ref('websites/');
ref.orderByChild("time").startAt(start).endAt(end).once('value', function (data) {
data.forEach(function (snapshot) {
content.push(snapshot.val());
})
});
return content;
},
>[]
0:Object
protocol:"https:"
time: 1496523823397
time_spent: 17
url:"www.google.ee"
__proto__:
1:Object
....
157:Object
....
console.log(这是今天的用法)
console.log(此.todays\u用法[0])
未定义的firebase是异步的,因此
todays\u用法在Master()完成后获取其内容。@wOxxOm是否可以关闭异步?我正在使用once而不是on获取数据。请重新编写代码以正确利用异步模型。