[js]js中函數傳參判斷


1,通過||

        function fun(x,y){
            x=x||0;
            y=y||1;
            alert(x+y);
        }
        fun();

2.通過undefined對比

       function fun(x,y){
            if(x==undefined){
                x=100;
            }
            y=y==undefined?200:y;
            alert(x+y);
        }
        fun();

3.通過argument

		function fun(x,y){
			x=arguments[0]?arguments[0]:100;
			y=arguments[1]?arguments[1]:200;
			return x+y;
		}
		alert(fun());
		alert(fun(1,2));

4,形參 實參 解釋argument

    function fn(a,b)
    {
        console.log(fn.length); //得到是 函數的形參的個數
        //console.log(arguments);
        console.log(arguments.length); // 得到的是實參的個數
        if(fn.length == arguments.length)
        {
            console.log(a+b);
        }
        else
        {
            console.error("對不起,您的參數不匹配,正確的參數個數為:" + fn.length);
        }
        //console.log(a+b);
    }
    fn(1,2);
    fn(1,2,3);


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM