2015-09-09 30 views
0

我正在练习递归,并试图构建一个函数来扫描对并将它们放在自己的列表中,只使用递归(no forEaches,loops等)。如果存在奇怪的元素,则添加一个零。这里是我的代码和一个示例输入/输出。我唯一缺少的是如何在最后处理未定义的情况。我将如何处理?递归放置在子列表中

function ownListPair(arr){ 

return arr.length < 2 ? [[arr[0], 0]] : [[arr[0], arr[1]]].concat(ownListPair(arr.slice(2))); 

} 


var arr = [2,7,8,3,1,4] 
//should return [ [ 2, 7 ], [ 8, 3 ], [ 1, 4 ]] 
console.log(ownListPair(arr)) 
//returns [ [ 2, 7 ], [ 8, 3 ], [ 1, 4 ], [ undefined, 0 ] ] 
//how do I handle the undefined case? I tried a check for if the length is 1 
and got "maximum call stack exceeded"... 

也尝试检查arr [0]没有与第一个长度检查一起未定义,但也调用堆栈错误。

回答

2

您需要一个arr.length === 0的情况。有许多的方法可以写这篇文章,这里有一个:

function ownListPair(arr){ 
 
    if (arr.length === 0) 
 
    return arr; 
 
    else if(arr.length === 1) 
 
    return [[arr[0], 0]]; 
 
    else 
 
    return [[arr[0], arr[1]]].concat(ownListPair(arr.slice(2))); 
 
} 
 

 
console.log(ownListPair([2,7,8,3,1,4]));
<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>