含义:
函数内部不断调用自身。递归函数的使用要注意函数终止条件避免死循环(一般都要写一个结束的条件);
//在递归的过程中会出错
// Maximum call stack size exceeded
// 内存溢出:超过了最大的堆栈大小
递归应用场景:
- 深拷贝
- 菜单树
- 遍历 DOM 树
示例
- 深拷贝
function deepCopy(o1, o2){
for(var key in o1){
var item = o1[key];
if(item instanceof Object){
o2[key] = {};
deepCopy(item, o2[key])
}else if(item instanceof Array){
o2[key] = {};
deepCopy(item, o2[key])
}else{ //基本类型的拷贝
o2[key] = o1[key];
}
}
}
var obj1 = {
name: 'zs',
age: 18,
dog:{
name:'xx',
age:2
},
friend:['lisi','ww']
};
var obj2 = {};
deepCopy(obj1, obj2);
obj1.name = 'name';
obj1.dog = 'dogname';
obj1.friend[0] = 'ls';
- 菜单树
var data = [{name:'分类1',children:[{name:'分类1-1',children:[{name:'分类1-1-1'}]},{name:'分类1-2'}]},{name:'分类2',children:[{name:'分类2-1'}]},{name:'分类3'}];
var tree = document.getElementById('tree');
createTree(tree, data)
function createTree(element, data){
var ul = document.createElement('ul');
element.appendChild(ul);
for(var i = 0; i < data.length; i++){
var li = document.createElement('li');
ul.appendChild(li);
li.innerText = data[i].name;
if(data[i].children.length > 0){
createTree(li, data[i].children)
}
}
}
- 遍历DOM树
//遍历li元素并添加点击事件
function loadTree(parent, callback){
for(var i = 0; i < parent.children.length; i++){
var child = parent.children[i];
if(callback){
callback(child);
}
loadTree(child);
}
}
var ul = document.querySelector('ul');
loadTree(ul, function(element){
element.onclick = function(){
console.log(this.innerText)
}
})