js递归和数组去重(简单便捷的用法)

1.递归例子
<script type="text/javascript"> function test(num) { if(num < 0) { return; } console.log('递归算法'); test(num - 1); } test(8); //打印九次 递归算法; </script>
2.递归求和 1-100
<script type="text/javascript"> function Sum(num) { if(num < 1) { return num = 0; } console.log('递归算法'); //打印100次 return Sum(num - 1) + num } var a = Sum(100) console.log(a) //结果是5050; </script>
3.递归阶乘 5 (5*4*3*2*1)
<script type="text/javascript"> function Sum(num) { if(num <= 1) { return 1; } console.log('递归算法'); return num*Sum(num - 1); //5 4 3 2 1 0 } var a = Sum(5); console.log(a); //120 </script>

 

4.数组去重 indexOf()
<script type="text/javascript"> var arr = [1, 2, 3, 4, 3, 6, 78, 8]; function dele() { var newArry = []; for(var i = 0; i < arr.length; i++) { if(newArry.indexOf(arr[i]) == -1) { newArry.push(arr[i]) } } console.log(newArry) //[1, 2, 3, 4, 6, 78, 8]; } dele(); </script>
5.拓展运算符(...)内部使用for...of循环
<script type="text/javascript"> let arr = [1, 2, 2, 3, 3]; let newArry = [...new Set(arr)]; console.log(newArry); //[1,2,3] </script>

 

posted @ 2018-04-16 00:32  鱼樱前端  阅读(1133)  评论(0编辑  收藏  举报