我具有以下按预期方式运行的计算属性。如果3个数据属性中的任何一个为空字符串,我希望它返回true;如果任何字符串为“ n / a”,我希望它返回true:
appNamesInvalid() {
if (!this.preferredAppName1 || !this.preferredAppName2 || !this.preferredAppName3) {
return true;
}
if (this.preferredAppName1.toLowerCase().includes('n/a') || this.preferredAppName2.toLowerCase().includes('n/a') || this.preferredAppName3.toLowerCase().includes('n/a')) {
return true;
}
return false;
},
我本来是想这样做的,但是这没有按预期工作,我也无法说出原因:
appNamesInvalid() {
let appNames = [this.preferredAppName1, this.preferredAppName2, this.preferredAppName3];
appNames.forEach(appName => {
if (appName == "" || appName.toLowerCase().includes("n/a")) {
return true;
}
}
return false;
},
是否有一种更干净的方法来重构第一块中的工作代码?
答案 0 :(得分:3)
尝试使用Array.prototype.some根据您的特定条件返回布尔值:
appNamesInvalid() {
let appNames = [this.preferredAppName1, this.preferredAppName2, this.preferredAppName3];
return appNames.some(appName => {
return appName === "" || appName.toLowerCase().includes("n/a");
}
},
如果true
或appName === ""
为真,则返回appName.toLowerCase().includes("n/a")
。
希望有帮助!