一.链表的递归遍历(常见)
递归遍历,必须有出口
// 链表的递归遍历
function Node(value){
this.value = value;
this.next = null;
}
var a = new Node(1);
var b = new Node(2);
var c = new Node(3);
var d = new Node(4);
var e = new Node(5);
a.next = b;
b.next = c;
c.next = d;
d.next = e;
function foreachLB(firstNode){
if(firstNode == null) return;//出口
console.log(firstNode.value);
foreachLB(firstNode.next);
}
foreachLB(a);
二.数组的递归遍历(不常用,一般用循环遍历)
// 数组的递归遍历
var arrList = [1,2,3,4,5,6,7,8];
function foreachArr(arr,i){
//i为需要从哪一位开始遍历
if(arrList == null || arrList.length <= i) return;
console.log(arrList[i]);
foreachArr(arrList,i+1);
}
foreachArr(arrList,0);