如何将字符串转换为 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;
});
});
}
这是我在控制台中的结果。我想将其转换为数组并循环它。
预期结果:应该有一条验证消息,通知选择 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/