簡體   English   中英

如何在打字稿中將這些對象轉換為數組

[英]How to convert these objects to array in typescript

如何將字符串轉換為 Typescript 數組? 請幫我。

看代碼:

private validateEmptyOption(): any {
    console.log("CHECKED")
    let isValid = true;
    this.currentForm.sections.forEach((section: Section) => {
        section.fields.forEach((field: Field) => {
            debugger
            if (field.type === 'select') {
                console.log(field)

                const emptyOptionSections = JSON.parse(field.property).emptyOptionSections;

                if ((emptyOptionSections !== undefined) && (emptyOptionSections == null)) {
                    alert('QAZWSX');
                    isValid = false;
                }
             }
        return isValid;
        });
    });
}

這是我在控制台中的結果。 我想做這個轉換為數組並循環它。

檢查這個

預期結果:應該有一條驗證消息通知選擇控制器不能為空

實際結果:表單無需任何驗證即可保存

如果您使用validateEmptyOption(): boolean您會得到提示,即您的函數不返回任何值。 問題是您的 return 語句 if 在其他函數中,因此不會被主要函數返回。

幾乎不需要使用any作為打字稿的類型。 (直到你做了非常復雜的事情......)

function validateEmptyOption(): boolean {
    console.log("CHECKED")

    return this.currentForm.sections.every((section: Section) => {
        return section.fields.every((field: Field) => {
            debugger
            if (field.type !== 'select') {
                return false;
            }

            console.log(field)

            try {
                const emptyOptionSections = JSON.parse(field.property).emptyOptionSections;
                if ((emptyOptionSections !== undefined) && (emptyOptionSections == null)) {
                    alert('QAZWSX');
                    return false;
                }
            } catch (e) {
                return false;
            }

            return true
        });
    });
}

every方法用於檢查每個值的內部函數是否返回 true。

因為你的return聲明寫錯了地方。 檢查您的{ } ( )

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM