我有一个带有 12 个布尔值的对象,我只想获取真值并插入到我的 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 []' 不能分配给类型 '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);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句