<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>菜鸟教程(runoob.com)</title> </head> <body> <p>设置参数的默认值。</p> <p id="demo"></p> <script> function myFunction(x, y) { if (y === undefined) { y = 0; } return x * y; } document.getElementById("demo").innerHTML = myFunction(4); </script> </body> </html>
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>菜鸟教程(runoob.com)</title> </head> <body> <p>设置函数参数默认值。</p> <p id="demo"></p> <script> function myFunction(x, y) { y = y || 0; return x * y; } document.getElementById("demo").innerHTML = myFunction(4); </script> </body> </html>
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>菜鸟教程(runoob.com)</title> </head> <body> <p>设置参数的默认值。</p> <p id="demo1"></p> <p id="demo2"></p> <script> function myFunction(x, y = 10) { // 如果不传入参数 y ,则其默认值为 10 return x + y; } // 输出 2 document.getElementById("demo1").innerHTML = myFunction(0, 2) ; // 输出 15, y 参数的默认值 document.getElementById("demo2").innerHTML = myFunction(5); </script> </body> </html>
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>菜鸟教程(runoob.com)</title> </head> <body> <p>查找最大的数。</p> <p id="demo"></p> <script> x = findMax(1, 123, 500, 115, 44, 88); function findMax() { var i, max = arguments[0]; if(arguments.length < 2) return max; for (i = 0; i < arguments.length; i++) { if (arguments[i] > max) { max = arguments[i]; } } return max; } document.getElementById("demo").innerHTML = x; </script> </body> </html>
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>菜鸟教程(runoob.com)</title> </head> <body> <p>计算所有参数之和:</p> <p id="demo"></p> <script> function sumAll() { var i, sum = 0; for(i = 0; i < arguments.length; i++) { sum += arguments[i]; } return sum; } document.getElementById("demo").innerHTML = sumAll(1, 123, 500, 115, 44, 88); </script> </body> </html>