Javascript函數(shù)原理

函數(shù)定義:
function 函數(shù)名稱(形式參數(shù)列表){
語句
}
調(diào)用函數(shù):
函數(shù)名稱(實(shí)際參數(shù)列表);
注意:
1)js的函數(shù)使用function定義,但是形式參數(shù)列表不能使用var關(guān)鍵詞
2)js的函數(shù)可以有返回值,直接使用return關(guān)鍵詞返回即可,不需要聲明返回值類型
3) js沒有方法重載的概念,后面定義的函數(shù)會覆蓋前面的函數(shù)。
4)js中的形式參數(shù)和實(shí)際參數(shù)的數(shù)量可以不一致,依然可以調(diào)用。
5)js的每個函數(shù)中都隱藏了一個叫arguments的數(shù)組,這個數(shù)組用于接收函數(shù)調(diào)用時傳遞過來的實(shí)際參數(shù)值。
6)arguments數(shù)組接收完實(shí)際參數(shù)后,會逐一的依次從左到右賦值給形式參數(shù),如果實(shí)際參數(shù)數(shù)量大于形式參數(shù),則丟失剩下的實(shí)際參數(shù)

    function add(a,b){ //a=10  b=20  40 
        //alert(arguments.length);
        for(var i=0;i<arguments.length;i++){
            document.write(arguments[i]+",");   
        }   
        var result = a+b;
        document.write("兩個參數(shù)的結(jié)果為:"+result); 
        //return result;
    }
    
    function add(a,b,c){ // a=10  b=20  c undefined  a+b+c=NaN
        var result = a+b+c;
        document.write("三個參數(shù)的結(jié)果為:"+result);
    }
    
    //var s = add(10,20);
    //document.write("返回值:"+s);
    add(10,20);
    

實(shí)際參數(shù)<形式參數(shù): NaN
實(shí)際參數(shù)>形式參數(shù): 取前面的實(shí)際參數(shù),后面的參數(shù)丟失

<script type="text/javascript">
    /*
    如果大月,顯示“該月有31天”
    如果小月,顯示“該月有30天”
    如果2月,顯示“該月有28天“
    */
    function check(){
        //alert("調(diào)用");  
        var month = document.getElementById("month").value; //表單輸入的內(nèi)容都是string類型!!
        //alert(typeof(month));
        //alert(month);
        
        //string和number比較,string會自動轉(zhuǎn)換成number類型,再進(jìn)行比較
        /*
        if(month==1 || month==3 || month==5 || month==7 || month==8 || month==10
            || month==12){
            alert("該月有31天");        
        }else if(month==4 || month==6 || month==9 || month==11){
            alert("該月有30天");    
        }else if(month==2){
            alert("該月有28天");    
        }else{
            alert("地球上沒有這個月份"); 
        }
        */
        
        //強(qiáng)制轉(zhuǎn)換
        month = parseInt(month);
        switch(month){
        case 1:
        case 3:
        case 5:
        case 7:
        case 8:
        case 10:
        case 12:
            alert("該月有31天");
            break;
        case 4:
        case 6:
        case 9:
        case 11:
            alert("該月有30天");
            break;
        case 2:
            alert("該月有28天");    
            break;
        default:
            alert("地球上沒有這個月份"); 
        }

    }

</script>
</head>

<body>
請輸入一個月份值:<input type="text" id="month"/><input type="button" value="查詢" onclick="check()"/>
</body>
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容