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

时间:2018-03-05 16:16:24

标签: arrays angular typescript

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

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

2 个答案:

答案 0 :(得分: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 :(得分:1)

正如@Teddy Sterne所评论的那样,您已经声明了randWordList两次并且正在使用randWordList中的范围subscribe,而您想要做的就是使用外部声明。< / p>

只需将日志记录移到forEach之外,您就可以按照自己的意愿行事,并按索引访问数组。

相关问题