<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <script type="text/javascript"> //声明一个函数 /*function myFun(){ alert("我是一个函数"); }*/ //函数的调用 // myFun(); //声明一个带有参数的函数 function add(num1,num2){ var sum=num1+num2; return sum; } /*console.log(add(3,5)); alert(add(99,789)); var s=add(-1,-9); //console.log(s); document.write('-1+-9='+s);*/ function myFunction(arg){ //如果arg是非数字,不做任何操作,否则返回arg的2倍 if(isNaN(arg)) return; return arg*2; } console.log(myFunction(40)); </script> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <script type="text/javascript"> /*function inner(){ //传到函数里的参数都存在arguments数组里 console.log(arguments.length); console.log(arguments[1]); //索引是从0开始的正整数 } inner(10,5); function add(num1,num2){ arguments[0]=99; console.log(num1); } add(55,88);*/ //求任意一组数的平均值 function getAvg(){ console.log(arguments.length); //对所有参数进行求和 var sum=0,len=arguments.length,i; for(var i=0;i<len;i++){ sum+=arguments[i]; //sum=0+5 //sum=0+5+66 //sum=0+5+66+45 } return sum/len; } var avg=getAvg(5,66,45,32,88,24,40,199,3900); console.log(avg); </script> </body> </html>