用 JavaScript 的方式理解递归

原文地址

1. 递归是啥?

递归概念很简单,“自己调用自己”(下面以函数为例)。

在分析递归之前,需要了解下 JavaScript 中“压栈”(call stack) 概念。

2. 压栈与出栈

是什么?可以理解是在内存中某一块区域,这个区域比喻成一个箱子,你往箱子里放些东西,这动作就是压栈。所以最先放下去的东西在箱子最底下,最后放下去的在箱子最上面。把东西从箱子中拿出来可以理解为出栈

所以得出结论,我们有个习惯,拿东西是从上面往下拿,最先放下去的东西在箱子的最底下,最后才能拿到。

在 JavaScript 中,调用函数时,都会发生压栈行为,遇到含 return 关键字的句子或执行结束后,才会发生出栈(pop)。

来看个例子,这个段代码执行顺序是怎样的?

function fn1() {return 'this is fn1'
}function fn2() {fn3()return 'this is fn2'
}function fn3() {let arr = ['apple', 'banana', 'orange']return arr.length
}function fn() {fn1()fn2()console.log('All fn are done')
}fn()
复制代码

上面发生了一系列压栈出栈的行为:

  1. 首先,一开始栈(箱子)是空的
  2. 函数 fn 执行,fn 先压栈,放在栈(箱子)最底下
  3. 在函数 fn 内部,先执行函数 fn1fn1 压栈在 fn 上面
  4. 函数 fn1 执行,遇到 return 关键字,返回 this is fn1fn1 出栈,箱子里现在只剩下 fn
  5. 回到 fn 内部,fn1 执行完后,函数 fn2 开始执行,fn2 压栈,但是在 fn2 内部,遇到 fn3,开始执行 fn3,所以 fn3 压栈
  6. 此时栈中从下往上顺序为:fn3 <= fn2 <= fnfn 在最底下
  7. 以此类推,函数 fn3 内部遇到 return 关键字的句子,fn3 执行完结束后出栈,回到函数 fn2 中 ,fn2 也是遇到 return 关键字,继续出栈。
  8. 现在栈中只有 fn 了,回到函数 fn 中,执行 console.log('All fn are done') 语句后,fn 出栈。
  9. 现在栈中又为空了。

上面步骤容易把人绕晕,下面是流程图:

再看下在 chrome 浏览器环境下执行:

3. 递归

先看下简单的 JavaScript 递归

function sumRange(num) {if (num === 1) return 1;return num + sumRange(num - 1)
}sumRange(3) // 6
复制代码

上面代码执行顺序:

  1. 函数 sumRange(3) 执行,sumRange(3) 压栈,遇到 return 关键字,但这里还马上不能出栈,因为调用了 sumRange(num - 1)sumRange(2)
  2. 所以,sumRange(2) 压栈,以此类推,sumRange(1) 压栈,
  3. 最后,sumRange(1) 出栈返回 1,sumRange(2) 出栈,返回 2,sumRange(3) 出栈
  4. 所以 3 + 2 + 1 结果为 6

看流程图

所以,递归也是个压栈出栈的过程。

递归可以用非递归表示,下面是上面递归例子等价执行

// for 循环
function multiple(num) {let total = 1;for (let i = num; i > 1; i--) {total *= i}return total
}
multiple(3)
复制代码

4. 递归注意点

如果上面例子修改一下,如下:

function multiple(num) {if (num === 1) console.log(1)return num * multiple(num - 1)
}multiple(3) // Error: Maximum call stack size exceeded
复制代码

上面代码第一行没有 return 关键字句子,因为递归没有终止条件,所以会一直压栈,造成内存泄漏。

递归容易出错点

  1. 没有设置终止点
  2. 除了递归,其他部分的代码
  3. 什么时候递归合适

好了,以上就是 JavaScript 方式递归的概念。

下面是练习题。

6. 练习题目

  1. 写一个函数,接受一串字符串,返回一个字符串,这个字符串是将原来字符串倒过来。
  2. 写一个函数,接受一串字符串,同时从前后开始拿一位字符对比,如果两个相等,返回 true,如果不等,返回 false
  3. 编写一个函数,接受一个数组,返回扁平化新数组。
  4. 编写一个函数,接受一个对象,这个对象值是偶数,则让它们相加,返回这个总值。
  5. 编写一个函数,接受一个对象,返回一个数组,这个数组包括对象里所有的值是字符串

7. 参考答案

参考1

function reverse(str) {if(str.length <= 1) return str; return reverse(str.slice(1)) + str[0];
}reverse('abc')
复制代码

参考2

function isPalindrome(str){ if(str.length === 1) return true;if(str.length === 2) return str[0] === str[1]; if(str[0] === str.slice(-1)) return isPalindrome(str.slice(1,-1)) return false; 
}var str = 'abba'
isPalindrome(str)
复制代码

参考3

function flatten (oldArr) {var newArr = [] for(var i = 0; i < oldArr.length; i++){ if(Array.isArray(oldArr[i])){ newArr = newArr.concat(flatten(oldArr[i])) } else { newArr.push(oldArr[i])}}return newArr;
}flatten([1,[2,[3,4]],5])
复制代码

参考4

function nestedEvenSum(obj, sum=0) {for (var key in obj) { if (typeof obj[key] === 'object'){ sum += nestedEvenSum(obj[key]); } else if (typeof obj[key] === 'number' && obj[key] % 2 === 0){ sum += obj[key]; }} return sum;
}nestedEvenSum({c: 4,d: {a: 2, b:3}})
复制代码

参考5

function collectStrings(obj) {let newArr = []for (let key in obj) {if (typeof obj[key] === 'string') {newArr.push(obj[key])} else if(typeof obj[key] === 'object' && !Array.isArray(obj[key])) {newArr = newArr.concat(collectStrings(obj[key]))}}return newArr
}var obj = {a: '1',b: {c: 2,d: 'dd'}}collectStrings(obj)
复制代码

5. 总结

递归精髓是,往往要先想好常规部分是怎样的,在考虑递归部分,下面是 JavaScript 递归常用到的方法

  • 数组:slice, concat
  • 字符串: slice, substr, substring
  • 对象:Object.assign

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/389420.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

PyTorch官方教程中文版:Pytorch之图像篇

微调基于 torchvision 0.3的目标检测模型 """ 为数据集编写类 """ import os import numpy as np import torch from PIL import Imageclass PennFudanDataset(object):def __init__(self, root, transforms):self.root rootself.transforms …

大数据数据科学家常用面试题_进行数据科学工作面试

大数据数据科学家常用面试题During my time as a Data Scientist, I had the chance to interview my fair share of candidates for data-related roles. While doing this, I started noticing a pattern: some kinds of (simple) mistakes were overwhelmingly frequent amo…

scrapy模拟模拟点击_模拟大流行

scrapy模拟模拟点击复杂系统 (Complex Systems) In our daily life, we encounter many complex systems where individuals are interacting with each other such as the stock market or rush hour traffic. Finding appropriate models for these complex systems may give…

公司想申请网易企业电子邮箱,怎么样?

不论公司属于哪个行业&#xff0c;选择企业邮箱&#xff0c;交互界面友好度、稳定性、安全性都是选择邮箱所必须考虑的因素。网易企业邮箱邮箱方面已有21年的运营经验&#xff0c;是国内资历最高的电子邮箱&#xff0c;在各个方面都非常成熟完善。 从交互界面友好度来看&#x…

莫烦Matplotlib可视化第二章基本使用代码学习

基本用法 import matplotlib.pyplot as plt import numpy as np""" 2.1基本用法 """ # x np.linspace(-1,1,50) #[-1,1]50个点 # #y 2*x 1 # # y x**2 # plt.plot(x,y) #注意&#xff1a;x,y顺序不能反 # plt.show()"""…

vue.js python_使用Python和Vue.js自动化报告过程

vue.js pythonIf your organization does not have a data visualization solution like Tableau or PowerBI nor means to host a server to deploy open source solutions like Dash then you are probably stuck doing reports with Excel or exporting your notebooks.如果…

plsql中导入csvs_在命令行中使用sql分析csvs

plsql中导入csvsIf you are familiar with coding in SQL, there is a strong chance you do it in PgAdmin, MySQL, BigQuery, SQL Server, etc. But there are times you just want to use your SQL skills for quick analysis on a small/medium sized dataset.如果您熟悉SQ…

第十八篇 Linux环境下常用软件安装和使用指南

提醒&#xff1a;如果之后要安装virtualenvwrapper的话&#xff0c;可以直接跳到安装virtualenvwrapper的方法&#xff0c;而不需要先安装好virtualenv安装virtualenv和生成虚拟环境安装virtualenv&#xff1a;yum -y install python-virtualenv生成虚拟环境&#xff1a;先切换…

莫烦Matplotlib可视化第三章画图种类代码学习

3.1散点图 import matplotlib.pyplot as plt import numpy as npn 1024 X np.random.normal(0,1,n) Y np.random.normal(0,1,n) T np.arctan2(Y,X) #用于计算颜色plt.scatter(X,Y,s75,cT,alpha0.5)#alpha是透明度 #plt.scatter(np.arange(5),np.arange(5)) #一条线的散点…

计算机科学必读书籍_5篇关于数据科学家的产品分类必读文章

计算机科学必读书籍Product categorization/product classification is the organization of products into their respective departments or categories. As well, a large part of the process is the design of the product taxonomy as a whole.产品分类/产品分类是将产品…

es6解决回调地狱问题

本文摘抄自阮一峰老师的 http://es6.ruanyifeng.com/#docs/generator-async 异步 所谓"异步"&#xff0c;简单说就是一个任务不是连续完成的&#xff0c;可以理解成该任务被人为分成两段&#xff0c;先执行第一段&#xff0c;然后转而执行其他任务&#xff0c;等做好…

交替最小二乘矩阵分解_使用交替最小二乘矩阵分解与pyspark建立推荐系统

交替最小二乘矩阵分解pyspark上的动手推荐系统 (Hands-on recommender system on pyspark) Recommender System is an information filtering tool that seeks to predict which product a user will like, and based on that, recommends a few products to the users. For ex…

莫烦Matplotlib可视化第四章多图合并显示代码学习

4.1Subplot多合一显示 import matplotlib.pyplot as plt import numpy as npplt.figure() """ 每个图占一个位置 """ # plt.subplot(2,2,1) #将画板分成两行两列&#xff0c;选取第一个位置,可以去掉逗号 # plt.plot([0,1],[0,1]) # # plt.su…

python 网页编程_通过Python编程检索网页

python 网页编程The internet and the World Wide Web (WWW), is probably the most prominent source of information today. Most of that information is retrievable through HTTP. HTTP was invented originally to share pages of hypertext (hence the name Hypertext T…

Python+Selenium自动化篇-5-获取页面信息

1.获取页面title title&#xff1a;获取当前页面的标题显示的字段from selenium import webdriver import time browser webdriver.Chrome() browser.get(https://www.baidu.com) #打印网页标题 print(browser.title) #输出内容&#xff1a;百度一下&#xff0c;你就知道 2.…

火种 ctf_分析我的火种数据

火种 ctfOriginally published at https://www.linkedin.com on March 27, 2020 (data up to date as of March 20, 2020).最初于 2020年3月27日 在 https://www.linkedin.com 上 发布 (数据截至2020年3月20日)。 Day 3 of social distancing.社会疏离的第三天。 As I sit on…

莫烦Matplotlib可视化第五章动画代码学习

5.1 Animation 动画 import numpy as np import matplotlib.pyplot as plt from matplotlib import animationfig,ax plt.subplots()x np.arange(0,2*np.pi,0.01) line, ax.plot(x,np.sin(x))def animate(i):line.set_ydata(np.sin(xi/10))return line,def init():line.set…

data studio_面向营销人员的Data Studio —报表指南

data studioIn this guide, we describe both the theoretical and practical sides of reporting with Google Data Studio. You can use this guide as a comprehensive cheat sheet in your everyday marketing.在本指南中&#xff0c;我们描述了使用Google Data Studio进行…

人流量统计系统介绍_统计介绍

人流量统计系统介绍Its very important to know about statistics . May you be a from a finance background, may you be data scientist or a data analyst, life is all about mathematics. As per the wiki definition “Statistics is the discipline that concerns the …

pyhive 连接 Hive 时错误

一、User: xx is not allowed to impersonate xxx 解决办法&#xff1a;修改 core-site.xml 文件&#xff0c;加入下面的内容后重启 hadoop。 <property><name>hadoop.proxyuser.xx.hosts</name><value>*</value> </property><property…