数组元素是未定义的,即使在推入元素后

我正在构build一个video保存服务作为一个项目,并从数据库response.array[]获取用户的已保存videoarrays,然后将videoId推入显示arraysvideo[]但显示相应的videoId使用console.log()它不断未定义。

我有如下的代码片段。

 let video = []; this.service.nextVideo().subscribe( response => { response.array.forEach(element => { video.push(element.videoId); }); }) console.log(video[0]); //Output is undefined 

完整的代码片段就像这样

 nxtVideo(){ let video = []; this.service.nextVideo().subscribe( response => { response.array.forEach(element => { console.log(element.videoId);//Display's video id video.push(element.videoId); }); }) console.log(video[0]); //Output undefined console.log(video); //Output shows all elements but on accessing specific elements it shows undefined return (video[this.offset++]); //offset is a global variable to measure watched videos } Launch(){ let videoId = this.nxtVideo(); //The Display table starts here } 

试试这个代码。 它必须是工作,因为它的asynchronousfunction。

 let video = []; this.service.nextVideo().subscribe( response => { response.array.forEach(element => { video.push(element.videoId); }); console.log(video[0]); //Output is undefined })