我是靠谱客的博主 无心电话,这篇文章主要介绍JS和Java如何模拟Python的for-else,现在分享给大家,希望可以做个参考。

复制代码
1
2
3
4
5
6
7
for i in input("input: "): if i == "a": print("a found") break else: print("a not found")

这个else不会在break时执行,只会在循环正常结束(循环条件不满足)时执行。
循环判断满足条件的值是否存在过的代码里,可以作为没有找到值的分支
但在别的语言里没有这样的语法

那么要怎么模拟呢

你可能会想到定义变量记录循环跳出
也可能想到利用函数的return

但是不要忘了
在Java和JS里,可以给代码块加标签
这个标签可以用来跳出这个代码块

复制代码
1
2
3
4
5
6
7
8
9
10
with_else: { for (const i of [1, 2, 4, 5]) { if (i == 3) { console.log("3 found"); break with_else; } } console.log("3 not found") }

Java同理

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class Test { public static void main(String[] args) { byte[] str = "asd_ghjkl".getBytes(); with_else: { for (int i = 0; i < str.length; i++) { if (str[i] == 'f') { System.out.println("f found"); break with_else; } } System.out.println("f not found"); } } }

这样比用变量记录状态和利用return都要简单

最后

以上就是无心电话最近收集整理的关于JS和Java如何模拟Python的for-else的全部内容,更多相关JS和Java如何模拟Python内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(80)

评论列表共有 0 条评论

立即
投稿
返回
顶部