初学函数的练手案例
作者:互联网
//简易函数:求累加和
1 var num = 0; 2 function getnum(num1,num2) { 3 for (var num1 = num1;num1 <= num2;num1++){ 4 num = num + num1; 5 } 6 console.log(num); 7 } 8 getnum(1,100);
//利用函数求最大值
1 function bijiao(num1,num2){ 2 /* if (num1>num2){ 3 return num1; 4 }else { 5 return num2; 6 }*/ 7 8 //也可以用三元表达式 9 return num1>num2?num1:num2; 10 } 11 console.log(bijiao(100,50))
//利用函数求列表中的最大值
1 function max(arr){ 2 var max1 = arr[0]; 3 for (var i = 1;i <= arr.length;i++){ 4 if(max1 < arr[i]){ 5 max1 = arr[i]; 6 } 7 } 8 return max1; 9 } 10 var zhi = max([50,101,52,30,54,60,70]); 11 console.log(zhi);
//利用函数判断是否是闰年;
1 function runnian(num) { 2 if (num % 4 == 0 && num % 100 != 0){ 3 return '这是闰年'; 4 }else if(num % 400 == 0){ 5 return '这是闰年'; 6 }else { 7 return '这不是闰年'; 8 } 9 } 10 var run = runnian(2012); 11 console.log(run);
标签:练手,function,return,num1,num2,num,案例,初学,var 来源: https://www.cnblogs.com/wang312/p/15923741.html