递归

129 阅读1分钟

递归的初识

1 语法:函数在函数内部调用自己 注意一定要有结束条件,不然会死循环

//01 函数内部调用自己
function test(){
	console.log('hello world')
    test()
}
test()

//函数内部间接调用函数自己
function test1(){
	console.log('test1')
    test2()
}
function test2(){
	console.log('test2')
    test1()
}
test1()

//注意:递归一定要有结束的时候
let i=0
function test3(){
	i++
    console.log('哈哈')
    if(i<3){
    	test3()
    }
}
test3()

递归的执行过程

let i=0
function ts(){
	i++
    console.log('哈哈'+i)
    if(i<3){
    	ts()
    }
    console.log('呵呵'+i)
}
ts()

递归案例

//利用递归求1到5 的和
function add(n){
	if(n==1){
    	return 1
    }
    return add(n-1)+n
}
add(5)

通过递归的方法遍历dom树的元素

用递归遍历打印1-n之间的每一个整数.