javascript - 返回 IF ELSE IF 语句的函数
问题描述
我正在尝试运行一段代码,它是一系列 IF ELSE IF 语句,用于检查某些条件是否为真。
if (2 > 1) {
return true;
}
else if (3 > 1) {
return true;
}
else if (4 > 1) {
return true;
}
else {
alert('Not all conditions are true')
}
它工作正常,但我想在最后添加一个函数,如果所有条件都为真,在下面的代码中我添加了该函数,但现在似乎在没有先检查所有条件的情况下运行该函数
if (2 > 1) {
return true;
}
else if (3 > 1) {
return true;
}
else if (4 > 1) {
return true;
}
else {
alert('Not all conditions are true')
}
// Run this function after checking all the conditions are true
allConditionsTrue();
我想我对应该放置函数的位置感到困惑。
任何帮助是极大的赞赏 :)
解决方案
对于任意计数的条件并且如果前一个条件是false
并且下一个条件是立即退出true
,您可以在someFalse
值出现时为状态取一个变量。
Afetr 检查所有条件检查someFalse
并返回'Not all conditions are true'
。
最后很明显,所有条件都是true
,您可以为这种情况调用函数。
function check(value) {
function allConditionsTrue() {
console.log('All conditions are true');
}
let someFalse = false,
conditions = [value < 2, value < 3, value < 4],
fn = c => c ? someFalse : !(someFalse = true);
if (conditions.some(fn)) return true;
if (someFalse) {
console.log('Not all conditions are true');
return false;
}
allConditionsTrue();
return true;
}
console.log(1, check(1));
console.log(2, check(2));
console.log(3, check(3));
console.log(4, check(4));
推荐阅读
- c++ - 将自定义运算符添加到 BOOST_STRONG_TYPEDEF 类型
- r - R:将difftime矩阵转换为整数矩阵进行除法
- postgresql - 在选择期间仅重命名一列
- python - Pandas to_csv 引发 IOError:没有这样的文件或目录
- nixos - 保留python环境
- android - Android:从 setErrorEnabled() 调用时,TextInputLayout ColorStateList.isStateful() 抛出异常
- java - Json路径获取所有第一个属性
- excel - 无法显示非模态 Excel 进度条
- flutter - 错误:在我的项目中导入颜色选择器包时方法“AlwaysWinPanGestureRecognizer...”的参数“事件”
- java - SPIGOT 插件中未处理的异常执行命令