在TypeScript中的函数中将对象添加到数组

时间:2018-09-19 09:06:22

标签: angular typescript

我有一个包含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类型'()中缺少'press'属性   =>字符串[]'。”,

1 个答案:

答案 0 :(得分:1)

您将函数分配给数组,这不行。如果要将数组的计算移至某个函数并将该函数的结果分配给该数组,则需要执行该函数。另外,如果您需要在函数(this.months)中使用实例Memebres,则应该使用箭头函数

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);