JavaScript的continue、break和return的区别
2024-10-09 12:06:22
1. continue、break和return的区别
循环遍历。
for(let i = 0; i < 5; i++){
console.log(i); // 0 1 2 3 4
}
使用continue
、break
和return
。
for(let i = 0; i < 5; i++){
if(i==3){
continue;
}
console.log(i); // 0 1 2 4
}
for(let i = 0; i < 5; i++){
if(i==3){
break;
}
console.log(i); // 0 1 2
}
for(let i = 0; i < 5; i++){
if(i==3){
return;
}
console.log(i); // 0 1 2
}
我们可以看到continue
跳出当前循环(即进入下次循环),而break
跳出整个循环(即不再执行之后的循环)。
这里return
也是跳出循环,但其实return
和break
是有区别的。我们再看几个例子。
(function foo(){
for(let i = 0; i < 5; i++){
if(i==3){
continue;
}
console.log(i); // 0 1 2 4 hello
}
console.log('hello');
})();
(function foo(){
for(let i = 0; i < 5; i++){
if(i==3){
break;
}
console.log(i); // 0 1 2 hello
}
console.log('hello');
})();
(function foo(){
for(let i = 0; i < 5; i++){
if(i==3){
return;
}
console.log(i); // 0 1 2
}
console.log('hello');
})();
提示:(function foo(){ //... })()
是立即执行函数。
我们看到使用return
时,没有打印hello
。因此,return
除了跳出循环的作用外,还有跳出当前函数的作用。
最新文章
- wxWidgets编译安装gtk问题的解决办法
- ural 2065. Different Sums
- 如何利用java得到当前的时间和前一天的时间
- Linux-vmware tools安装与cdrom挂载
- 7.适配器模式(Adapter Pattern)
- ROC和AUC介绍以及如何计算AUC
- Spring Data与elasticsearch版本对应关系
- 对FMDB的封装JRDB
- 学习MQ(一) 感知
- 201771010126 王燕《面向对象程序设计(java)》第二周学习总结
- cf1088D Ehab and another another xor problem (构造)
- python绘图工具matplotlib在linux下安装和使用
- 集合框架-Set集合
- 关于在pycharm下提示ModuleNotFoundError: No module named &#39;XXX&#39; 的一种可能
- 分页sql写法【只用最新的】
- video兼容--可用
- 【概率论】条件概率 &; 全概率公式 &; 朴素贝叶斯公式
- Nginx安装负载均衡配置 fair check扩展
- 阿里历年经典Java面试题汇总,想进BAT你还不快收藏!
- cent os 6.5 配置vsftpd