javascript - 在 TypeScript 中获取日期的周数
问题描述
我有一个包含其他类的类
export class Sensor {
public id: string;
public label: string;
public measures: Measure[];
constructor(dbDate){
}
}
export class Message {
public id: string;
public arrivalTimestamp: Date;
public sensors: Sensor[];
constructor(dbData: any) {
this.id= dbData.id;
this.arrivalTimestamp= dbData.value.timestamp ;
this.sensors = new Sensor(dbData);
}
}
我实际上面临问题:Type 'Sensor' is not assignable to type 'Sensor[]'.
Property 'length' is missing in type 'Sensor'.
sensors
有一个类型,Array of Sensor
但我在构造函数中影响它的是 type Sensor
。
我试图添加刹车new Sensor[](dbData);
,但它不起作用我收到 VS Code 警告消息An element access expression should take an argument.
解决方案
您想要的只是拥有一个元素的数组,而不是“传感器阵列”类型的元素。
在 javascript 中,您可以动态创建一个数组,只需用方括号将变量括起来:
this.sensors = [new Sensor(dbData)];
这样一来this.sensors
,总会有一个元素。否则,您也可以将sensors
变量初始化为空数组:
public sensors: Sensor[] = [];
然后使用推送方法:
this.sensors.push(new Sensor(dbData));
此方法会将元素添加到数组中
推荐阅读
- ios - 使用单个按钮 iOS Swift 并排显示多个按钮
- ios - 如何使用 Swift 清除 SearchBar 结果并在 tableview 中显示完整数据?
- google-maps - 如何在颤动的谷歌地图上绘制折线
- c# - 使用 Identity Server 时是否必须登录到每个 Web 应用程序?
- android - 支持 Api 24 和 Api 26 的 Room 日期时间转换器
- mongodb - 有没有办法通过 apache-spark 流式传输数据以及读取 MongoDB 中已经存在的数据
- arrays - undefined 不是函数 data[index].push
- c - 如何理解指针数组的类型转换?
- openlayers - OpenLayers 可以仅更改倍数而不是中间图像的大小(使用 ol.source.Zoomify 的参数“大小”)吗?
- json - 使用 JSON 创建节点之间的链接/关系时未定义变量