JavaScript函数

函数

  语法:

    function name(参数1,参数2,参数3){

      执行的代码

    }

  参数1,参数2,参数3都为函数的形参

  函数作用:进行复用,只要定义一次代码,就可以多次使用它

  注意:函数名称严格区分大小写

     函数名称重复会产生覆盖

     函数名称可以包含字母、下划线、美元符号

  例:

    var x = myFunction(4,3);         //调用函数,返回值被赋值给x

    document.write(x);

    function myFunction(a,b){

      return a*b;               //函数返回a和b 的乘积

    }

              结果为 12

         执行函数时到达return语句,函数将停止执行。函数通常会计算出返回值。这个返回值会返回给调用者。

  

  例:

    function myFunction(a,b){

      return a*b;               

    }

    document.write(myFunction);

    document.write(myFunction(3,4);

   结果:function myFunction(a,b){        return a*b;      }12

  通过上名的例子,myFunction引用的是函数对象,而myFunction()引入函数的结果。

 函数使用的几种情况

  1、声明局部变量

    var x=1;
    function myfunction(){

      document.write(x);  

      var x=18;
      document.write(x);
    }
    myfunction();

   结果:undefined18

    var x=1;
    function myfunction(){
      document.write((x));
      x=18;
      document.write(x);
    }
    myfunction();

   结果:118

  局部变量:函数内声明的变量

  当函数中声明局部变量前输出时,函数调用全局变量实参时结果为underfined

  var x=18; 与x=18是不同的,var是声明变量,而x=18是赋值

   2、结果为undefined

    function my(){
      return;                         //无明确的返回值
    }
    alert(my());

     function my_(i,j){
      x=4;                          //没有return语句
    }
    alert(my_(2,3));

  上面两个例子,结果都为undefined,

  通过以上发现如果函数无明确的返回值,或调用时没有参数的return语句,那么它真正返回的值是undefined。

  3、结果为NaN

    function my_m(i,j){
      return x=i*j;
    }
    alert(my_m());

  结果为NaN,实参没有值

  4、其它

  function test2(){
    //return null;         // 1
    //return undefined;        //NaN
    //return;              //NaN     return没有明确的值,返回是undefined,undefined+1 ------> NaN
    //return true;         //2
    //return 'this is king';            //thid is king1
    //return 1.2;                        //2.2
    //return alert('this is a test');         //先弹出警示框,后控制台显示NaN
    //return 1;                          //2
  }
  console.log(test2()+1);

  alert(typeof (alert('this is a test')));     //先弹出this is a test警示框 ,后弹出undefined警示框

  5、实参多于形参(形参有几个取几个,形参只能用一次

    function calc(num1,num2){

      return num1+num2;
    }

    alert(calc(1,2,3,4,5,6));

   结果:3

  6、形参赋值(实参的值权重大于形参

    function calc1(num1=1,num2=2){
      return num1+num2;
    }

    alert(calc1(4,6));

  结果:10

  7、function calc1(num1,num2){

      num1=num1||1;
      num2=num2||2;
      return num1+num2;
    }
    alert(calc1(4,6));

    结果为10,num1=4;num2=6,num1=num1||1和num2=num2||2第一个表达式为true,整个结果为true,把第二个表达式短路。所以最后num1=4; num2=6。num1+num2所以结果为10。



原文地址:https://www.cnblogs.com/hebizaiyi/p/11351860.html