JS实现水平遍历和嵌套递归操作示例
作者:zhensg 时间:2024-04-22 12:48:01
本文实例讲述了JS实现水平遍历和嵌套递归操作。分享给大家供大家参考,具体如下:
程序中存在着一些有意思的逻辑,比如多层嵌套可以用递归遍历,比如同层的if else可以用数组遍历。
下面举例说明,多层嵌套的if else想要递归遍历需要写成下面的形式,以及用特定形式的递归遍历:
多层嵌套的if else转写成的函数
let p1 = false,
p2 = true,
p3 = false;
let test = function() {
if (p1) {
return '终止1';
} else {
return function() {
if (p2) {
return '终止2'
} else {
return function() {
if (p3) {
return '终止3'
}
}
}
}
}
}
对多层嵌套的遍历:
function yunxing1() {
while (test()) {
test = test()
if (typeof test === 'string') {
alert(test)
return '终止'
}
}
}
yunxing1()
同层多个if else改写的函数以及遍历方法
let i = 1,
a = 2,
b = 3;
function simpleVlidate() {
let varr = [];
varr.push(() => {
if (i === 1) {
return '不能等于1'
}
})
varr.push(() => {
if (a === 2) {
return '不能等于2'
}
})
varr.push(() => {
if (b === 3) {
return '不能等于3'
}
})
return varr
}
let arrs = simpleVlidate();
function yunxing() {
for (let i = 0, fn; fn = arrs[i++];) {
if (fn()) {
alert(fn())
return;
}
}
console.log(343433333333)
}
yunxing();
以上,总结的有意思的逻辑,也是可以简化代码的方法。这样的逻辑还有很多………………
希望本文所述对大家JavaScript程序设计有所帮助。
来源:https://www.cnblogs.com/zhensg123/p/10753114.html
标签:JS,遍历,递归
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
自动备份Oracle数据库
2024-01-20 15:08:14
Python使用pyecharts绘制世界地图,省级地图,城市地图实例详解
2022-08-08 06:37:22
![](https://img.aspxhome.com/file/2023/9/72119_0s.jpg)
Python实现的下载8000首儿歌的代码分享
2021-02-03 05:41:51
一步步教你在Navicat上如何停止正在运行的MYSQL语句
2024-01-21 06:17:01
![](https://img.aspxhome.com/file/2023/0/67090_0s.png)
Python button选取本地图片并显示的实例
2023-10-06 15:56:32
vue生成随机验证码的示例代码
2023-07-02 16:57:09
![](https://img.aspxhome.com/file/2023/3/139843_0s.png)
手把手教你Navicat如何导出Excel格式的表结构
2024-01-20 21:39:36
![](https://img.aspxhome.com/file/2023/8/105658_0s.jpg)
go语言LeetCode题解1030距离顺序排列矩阵单元格
2024-05-22 10:09:19
用ASP和SQL语句动态的创建Access表
2008-10-14 16:59:00
一百行python代码将图片转成字符画
2023-05-06 05:49:15
![](https://img.aspxhome.com/file/2023/1/99701_0s.png)
在Python开发环境中调用ChatGPT模型详细过程
2022-03-25 21:59:29
![](https://img.aspxhome.com/file/2023/3/97603_0s.jpg)
PyTorch一小时掌握之图像识别实战篇
2023-01-28 00:08:01
![](https://img.aspxhome.com/file/2023/3/134583_0s.png)
uwsgi+nginx部署Django项目操作示例
2021-05-04 02:23:50
![](https://img.aspxhome.com/file/2023/5/97045_0s.png)
MySQL DQL语句的具体使用
2024-01-21 08:17:03
如何基于Python实现自动扫雷
2023-12-13 15:51:08
![](https://img.aspxhome.com/file/2023/8/85128_0s.jpg)
php查询mysql数据库并将结果保存到数组的方法
2023-07-20 17:47:32
用ASP对网页进行限制性的访问
2008-07-03 13:02:00
Python tensorflow与pytorch的浮点运算数如何计算
2023-06-28 14:13:15
![](https://img.aspxhome.com/file/2023/2/95442_0s.jpg)
python3 实现除法结果为整数
2023-06-27 20:08:22
![](https://img.aspxhome.com/file/2023/6/118546_0s.jpg)
ASP中CACHE缓存技术
2010-05-03 10:58:00