Arrays Can';数组的t访问元素
我正在使用一个服务向数组中添加元素,该服务成功地添加了元素。我可以看到用console.log填充的数据 但是,我无法访问该元素Arrays Can';数组的t访问元素,arrays,angular,observable,Arrays,Angular,Observable,我正在使用一个服务向数组中添加元素,该服务成功地添加了元素。我可以看到用console.log填充的数据 但是,我无法访问该元素 this.routingService.getNode(startNode).subscribe(node => { node.forEach(node => { this.openSet.push(new MapNode(node.id, node.lon, node.lat, this.routingService.getN
this.routingService.getNode(startNode).subscribe(node => {
node.forEach(node => {
this.openSet.push(new MapNode(node.id, node.lon, node.lat, this.routingService.getNodeNeighbours(node.id)));
});
});
console.log(this.openSet); // this prints out the below screenshot
但是,当我使用以下内容时:
console.log(this.openSet[0]);
我得到“未定义”的输出。我不确定我现在是否真的很难理解如何访问它
有什么想法吗?
subscribe
是异步工作的,因此console.log()
将在forEach
循环运行之前进行日志记录。这与这段代码中的异步行为相同
让foo=[];
设置超时(()=>{
foo.push(1);
foo.push(2);
}, 500);
console.log(foo);//logs[]
您可以发布您在执行console.log(JSON.stringify(this.openSet))时看到的内容吗;请将javascript标记添加到问题@baao的可能重复项中,该问题如何与您提到的问题重复。你能详细解释一下吗?在社区维基答案中解释说@AravindAh,我明白你的意思。使用JSON.stringify打印出数组返回空,因此确认您的答案。谢谢!:)