gpt4 book ai didi

arrays - TS | array[n] 返回未定义,数组返回正确

转载 作者:搜寻专家 更新时间:2023-10-30 21:28:12 27 4
gpt4 key购买 nike

我有一个函数,它将每个键从 Firebase 推送到数组,以便在项目中进一步使用。

// component.ts
let x = this.wordService.getWords();
let randWordList: any[] = new Array();
x.snapshotChanges().subscribe(word => {
word.forEach(element => {
randWordList.push(element.key);
// here it works correct
console.log(randWordList[0]);
// throw in console -L6VLfqZqj8AeYT_0jwt
});
});

当我按名称检查控制台整个数组时,它输出正确,但我无权访问随机数组成员。

console.log(randWordList);
// outputs []
// "0": -L6VLfqZqj8AeYT_0jwt
// ...
// length: 8
console.log(randWordList[3]);
// return undefined;
console.log(randWordList["3"]);
// return undefined;

希望有人能帮助我理解我做错了什么。

最佳答案

您声明了 randWordList 变量两次。这使得订阅工作,但随后在回调之外,变量保留了它的空列表的原始值。

更改为:

// component.ts
public someFunction() {
let x = this.wordService.getWords();
let randWordList: any[] = new Array();
x.snapshotChanges().subscribe(word => {
word.forEach(element => {
randWordList.push(element.key);
console.log(randWordList[0]); // => "-L6VLfqZqj8AeYT_0jwt"
});

// use randWordList here since it is now populated.

});

console.log(randWordList[0]); // => undefined (subscribe callback has not been called)
}

关于arrays - TS | array[n] 返回未定义,数组返回正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49114833/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com