我有一个带有12个布尔值的对象,我想只得到值true并插入我的ArrayList中,但是我得到了错误。
let arrayMonths: Array<string> = function () {
let array: Array<string>;
let obKeys = Object.keys(this.months), prop: string;
for (prop of obKeys) {
if (this.months[prop]) {
array.push(this.service.months[prop]);
}
}
return array;
}
错误:
“message”:“类型'()=>字符串[]'不能分配给'string []'类型。\ n''=> string []'类型中缺少'press'属性“。 ,
您将一个函数分配给一个数组,这是不行的。如果要将数组的计算移动到函数并将函数的结果分配给数组,则需要执行该函数。如果你需要在函数内部使用实例memebrs,你应该使用箭头函数(this.months
)
let arrayMonths: Array<string> = (() => {
let array: Array<string> = []; //must initialize
for (let month of this.months) { // for - of a simpler option in this case if this.months is string[], you don't provide the definition of this though.
if (month) {
array.push(month);
}
}
return array;
})();
注意
如果你只想过滤数组Array.filter
将是更好的选择:
let arrayMonths: Array<string> = this.months.filter(m => !!m);