我正在使用Angular(so typescript)进行打印。我尝试遍历一个对象
我在这样的服务中构建对象:
class Point {
id: number;
name: string;
constructor(id: number, name: string) {
this.id = id;
this.name = name;
}
}
我用从数据库中获得的这些点填充数组
private pointList: Point[] = [];
我很乐意以角度的方式取回其他“组件”中的这些论点
getPointsList() {
return this.pointList;
}
所有这些都是在points.service.ts中完成的
所以问题是
在另一个组件中,我将这些点加载到局部变量中
pointList = this.pointsService.getPointsList();
zh_CN然后,我尝试像这样遍历它们:
console.log(this.pointList); // first consoleLog
for (const point of this.pointList) {
console.log(point); // second consoleLog
console.log(point.id); // third consoleLog
}
所有这些都是在另一个文件map.ts中完成的
console.log的结果是:
包含我的对象的数组,例如:[{{id:1 name:'test'} {{id:2 name:'test2'}]我认为这很正常
没有
没有
所以我认为它不会进入for循环,但是我不明白为什么。
我也试过了
到console.log(this.pointList[0])
但返回未定义
this.pointList.forEach(point => {console.log(point)});
但它没有打印任何东西
这是我的“真实”代码及其在控制台中显示的内容:
有人可以告诉我我在做什么错吗?
谢谢
您可能会尝试在填充数组之前查看这些值。它似乎适用于
console.log(this.pointList);
但这是因为在控制台窗口中显示的数组是动态的:在控制台窗口中展开数组时,它显示的值与console.log
执行语句时不同。
要在console.log
执行语句时看到数组的样子,请使用以下语句:
console.log(JSON.stringify(this.pointList));
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句