1 <!DOCTYPE html>
2 <html lang="zh">
3 <head>
4 <meta charset="UTF-8">
5 <meta name="viewport" content="width=device-width, initial-scale=1.0">
6 <meta http-equiv="X-UA-Compatible" content="ie=edge">
7 <title>Document</title>
8 </head>
9 <body>
10
11 <script>
12
13 // 形参:创建函数时声明的参数。
14 // 实参:调用函数时(实际)传入的参数。
15 // JS 中的函数不限制参数的数量,也不限制参数的类型。
16 function foo (x, y, z) {
17 // 函数体内有一个 arguments 类似于数组的对象,对象中保存着所有传入的实参
18 console.log(arguments)
19 console.log(arguments.length) // 实参的数量
20 console.log(foo.length) // 形参的数量
21 if (x > y) {
22 return x;
23 } else {
24 return y;
25 }
26 }
27
28
29 // JS 中的函数不限制参数的数量
30 // console.log(foo(12))
31 console.log(foo(12, 34, 56, 67))
32
33 // 也不限制参数的类型
34 // console.log(foo('abc', true))
35
36 // 形参的作用:能够标识函数所需参数的数量
37 function bar () {
38 if (arguments[0] > arguments[1]) {
39 return arguments[0];
40 } else {
41 return arguments[1];
42 }
43 }
44
45 // 形参的作用:能够明确地表示每个参数的意义
46 function fullName (firstName, lastName) {
47
48 return firstName + lastName;
49 // return arguments[0] + arguments[1];
50
51 }
52
53 // console.log(fullName('马什么', '梅'))
54
55 // arguments 对象的使用场景:求任意数量的数字的和
56
57 function sum () {
58 var result = 0;
59
60 for(var i = 0, len = arguments.length; i < len; i++) {
61 result += arguments[i]
62 }
63
64 return result;
65 }
66
67 // console.log(sum(1, 2, 3 , 4, 5))
68
69
70
71 </script>
72 </body>
73 </html>