javascript中的函数学习

来源:互联网 发布:手机音频分析软件 编辑:程序博客网 时间:2024/06/05 22:47

主要学习一下javascript中函数的使用:

<html><head><script src="jquery.js"></script><script>    console.log("12334");    var b=5;    var c=Math.sqrt(b);    console.log(c);    function distance(x1,y1,x2,y2){        dx=x2-x1;        dy=y2-y1;        return Math.sqrt(dx*dx+dy*dy);    }    var total=distance(0,0,2,1)+distance(2,1,3,5);    console.log(total);</script></head><body></body></html>

可以看到输出结果为:

12334 exam.html:52.23606797749979 exam.html:86.35917360311745 

javascript中方法的调用

<html><head><script src="jquery.js"></script><script>    var calculator={        operand1:1,        operand2:2,        add:function(){        this.result=this.operand1+this.operand2;        }    };    calculator.add();    var res=calculator.result;    console.log(res);</script></head><body></body></html>

输出结果为3

javascript中函数异常的抛出

<html><head><script src="jquery.js"></script><script>    function f(x,y,z)    {        if(arguments.length !=3){        throw new Error("function have "+arguments.length+"expexct 3 arguments");        }    }    f(4,5);</script></head><body></body></html>

用Chrome调试的时候看到如下错误提示:



可变长的实参列表:


<html><head><script src="jquery.js"></script><script>    function max(){    var max=Number.NEGATIVE_INFINITY    for(var i=0;i<arguments.length;i++)    {        if(arguments[i]>max){max = arguments[i];}    }        return max;    }    var largest=max(1,10,1000,908);    console.log(largest);</script></head><body></body></html>

输出结果为:1000

参考资料:

[javascript 权威指南]