在 TypeScript 中使用 forEach 返回布尔值



我想检查我的数组,如果我得到 3 ,我想打破我的 forEach,如果它不真实,则返回 true o false。

但是当我在我的 html 中推送 3 时,我变得未定义-

let errorSave: boolean = this.checkParams();
console.log("errorSave" , errorSave); // UNDEFINED
checkParams() {
let errorSave = this.params.forEach(element => {
if (element.origin === 3) {
return true;
}
});
return errorSave;
}

你试过用find吗?

checkParams() {
return !!this.params.find(element => element.origin === 3);
}

使用 indexOf 而不是 foreach 子句。

array=[1,2,3];
return this.array.indexOf(3)>-1;

最新更新