我尝试在angular2(typescript)中向数组添加元素。它既不会抛出任何错误,也不会将元素添加到数组中。
代码段:
let _dataSets:number[] = new Array(this.paymentModes.length);
for (let i = 0; i < this.paymentModes.length; i++) {
let paymentMode = this.paymentModes[i];
_dataSets.push(paymentMode.paymentModeTotalSales);
}
console.log(_dataSets);
有什么不对吗?
* paymentModes是来自WS响应的数组。
答案 0 :(得分:0)
使用数组映射,确保属性paymentMode.paymentModeTotalSales的类型为number,否则转换为;将默认值设置为0:
let dataSets:number[];
dataSets = this.paymentModes.map(paymentMode => Number(paymentMode.paymentModeTotalSales || 0));
console.log(dataSets);
答案 1 :(得分:0)
我能看到的唯一原因是paymentModeTotalSales不是数字。 例如,以下工作正常。您可以在警报中看到值10。您可以尝试运行此here
module Test {
class PaymentMode {
public paymentModeTotalSales: number;
constructor (paymentModeTotalSales: number) {
this.paymentModeTotalSales = paymentModeTotalSales;
}
}
let _dataSets: PaymentMode[] = [];
let _paymentModes: PaymentMode[] = [];
_paymentModes.push(new PaymentMode(10));
_paymentModes.push(new PaymentMode(12));
for (let i = 0; i < _paymentModes.length; i++) {
let paymentMode = _paymentModes[i];
_dataSets.push(new PaymentMode(paymentMode.paymentModeTotalSales));
}
alert(_dataSets[0].paymentModeTotalSales);
}