TS | array [n]返回undefined,数组返回正确

问题描述 投票:2回答:2

我有一个函数,它将每个键从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;

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

arrays angular typescript
2个回答
2
投票

你是两次声明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) 
}

1
投票

正如@Teddy Sterne评论的那样,你已经宣布randWordList两次并且在randWordList中使用范围的subscribe,而你想要做的就是使用外部声明。

只需将日志记录移动到forEach之外,然后您就可以执行所需操作并按索引访问数组。

© www.soinside.com 2019 - 2024. All rights reserved.