我有一个嵌套的if...else
块。
我想要一个初始条件,如果它通过了条件,它应该检查下一个条件。如果第二个条件失败,我希望它执行一个 else 块。
是否可以使用if...else
语句来执行此操作,或者我应该使用其他语句?
下面是一个示例:
let x = 1;
let y = 2;
let z = 3;
if (x == 1) {
console.log(x)
// the below statement would fail and I would like the else block to execute now, console.log(z)
if (y == 3) {
console.log(y)
}
} else {
console.log(z);
}
编辑:
我的问题是,如果 2 个条件中的任何一个失败,我需要相同的代码来运行,并且我不知道该怎么做。
if (condition == true) {
if (condition == true) {
func1()
} else {
ApiCall1()
}
} else {
ApiCall1()
}
有人告诉我我不能为APiCall1
创建一个函数,我必须把它全部写出来,所以我不能只是复制和粘贴两个块中ApiCall1
的代码,因为它有 30 行长。我应该在这里做什么?
从您在答案中的描述来看,我相信您只是想将 else 块移动到初始if
语句的块内 (if (x==1) {...}
(
因此:
if (x == 1) {
console.log(x)
if (y == 3) {
console.log(y)
}
else {
console.log(z);
}
}
为了补充其他答案,我不确定您是否要在第一个条件失败时执行else
块。如果是这种情况,那么您可以尝试:
if (x == 1 && y == 3) {
console.log(x)
console.log(y)
} else if (x == 1) {
console.log(x)
} else {
console.log(z)
}
你重复一些代码,但我认为没有其他方法可以做到这一点,至少我能想不出。
编辑:
在您编辑后,我认为这个解决方案更有意义,这样您就可以在上面解决方案的 else 块中拥有ApiCall1
的代码。