JavaScript(四)---- 函数

函数主要用来封装具体的功能代码。

函数是由这样的方式进行声明的:关键字 function、函数名、一组参数,以及置于括号中的待执行代码。

格式:

  function 函数名(形参列表){
        函数体 ;    
    }

javascript的函数要注意的细节:
    1. 在 javascript中函数定义形参时是不能使用var关键字声明变量的,直接写参数名即可。
    2. 在javascript中的函数是没有返回值类型 的,如果函数需要返回数据给调用者,直接返回即可,如果不需要返回则不返回。
    3. 在 javascript中是没有函数重载的概念的,后定义的同名函数会直接覆盖前面定义同名函数。
    4. 在javascript中任何的函数内部都隐式的维护了一个arguments(数组)的对象,给函数 传递数据的时候,是会先传递到arguments对象中,
    然后再由arguments对象分配数据给形参的。

代码示例

 1 <html xmlns="http://www.w3.org/1999/xhtml">
 2 <head>
 3 <script>
 4 
 5     function showDay(){
 6         //找到对应 的标签对象。
 7         var inputObj = document.getElementById("month");
 8         //获取input标签数据
 9         var month = inputObj.value;
10         /*
11         if(month==1||month==3||month==5||month==7||month==8||month==10||month==12){
12             alert("本月是31天");    
13         }else if(month==4||month==6||month==9||month==11){
14             alert("本月是30天");    
15         }else if(month==2){
16             alert("本月是28天");    
17         }else{
18             alert("没有该月份");    
19         }
20         */
21         
22         month = parseInt(month);
23         switch(month){
24             case 1:
25             case 3:
26             case 5:
27             case 7:
28             case 8:
29             case 10:
30             case 12:
31                 alert("本月是31天");
32                 break;
33             case 4:
34             case 6:
35             case 9:
36             case 11:
37                 alert("本月是30天");
38                 break;
39             case 2:
40                 alert("本月是28天");
41                 break;
42             default:
43                 alert("没有该月份");
44                 break;
45         
46         }
47         
48         
49     }
50 
51 
52 </script>
53 
54 
55 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
56 <title>无标题文档</title>
57 </head>
58 <body>
59     月份:<input id="month" type="text" /><input type="button" value="查询" onclick="showDay()" />
60 
61 </body>
62 </html>

注意:从网页中获取到的数据都是string类型。

原文地址:https://www.cnblogs.com/nicker/p/6290346.html