javascript - 如何在 typescript 中将这些对象转换为数组

标签 javascript arrays angular 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;
        });
    });
}

这是我在控制台中的结果。我想将其转换为数组并循环它。

Check This

预期结果:应该有一条验证消息,通知选择 Controller 不能为空

实际结果:表单无需任何验证即可保存

最佳答案

如果您使用validateEmptyOption(): boolean,您会得到提示,您的函数不会返回任何值。问题是你的 return 语句如果在其他函数内部,因此不会被主函数返回。

几乎从不需要使用any作为 typescript 的类型。 (直到你做了非常复杂的事情......)

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 method用于检查内部函数是否为每个值返回 true。

关于javascript - 如何在 typescript 中将这些对象转换为数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59539043/

相关文章:

php - PHP输出到文件以供下载,而无需在服务器上创建文件

javascript - 二进制数的 Angular 输入掩码

javascript - 有没有一个函数可以测试一个在js中有回调的对象实例?

arrays - 对多个索引的元组数组进行排序,在 Julia 中只有一个反转

javascript - 如何在页面卸载时执行 ajax 调用?

javascript - 如何在 Javascript 中计算对象数组内的值?

javascript - Angular2如何做一个url查询字符串

css - Angular 2 : displaying items in row/column fashion

javascript - jQuery 在页面加载时分配单击事件处理程序

javascript - 添加过渡效果