08-函数、09-伪数组 arguments

08-函数

 

函数:就是将一些语句进行封装,然后通过调用的形式,执行这些语句。

函数的作用:

  • 将大量重复的语句写在函数里,以后需要这些语句的时候,可以直接调用函数,避免重复劳动。

  • 简化编程,让编程模块化。

复制代码
  console.log("hello world");
    sayHello();     //调用函数
    //定义函数:
    function sayHello(){
        console.log("hello");
        console.log("hello world");
    }
复制代码

第一步:函数的定义

函数定义的语法:

 function 函数名字(){

    }

解释如下:

  • function:是一个关键字。中文是“函数”、“功能”。

  • 函数名字:命名规定和变量的命名规定一样。只能是字母、数字、下划线、美元符号,不能以数字开头。

  • 参数:后面有一对小括号,里面是放参数用的。

  • 大括号里面,是这个函数的语句。

第二步:函数的调用

函数调用的语法:

 函数名字();

函数的参数:形参和实参

函数的参数包括形参和实参

注意:实际参数和形式参数的个数,要相同。

例子:

复制代码
        sum(3,4);
        sum("3",4);
        sum("Hello","World");

        //函数:求和
        function sum(a, b) {
            console.log(a + b);
        }
复制代码

函数的返回值

例子:

复制代码
       console.log(sum(3, 4));

        //函数:求和
        function sum(a, b) {
            return a + b;
        }
复制代码

 

09-伪数组 arguments

 

arguments代表的是实参。有个讲究的地方是:arguments只在函数中使用

(1)返回函数实参的个数:arguments.length

例子:

复制代码
    fn(2,4);
    fn(2,4,6);
    fn(2,4,6,8);

    function fn(a,b,c) {
        console.log(arguments);
        console.log(fn.length);         //获取形参的个数
        console.log(arguments.length);  //获取实参的个数

        console.log("----------------");
    }
复制代码

结果:

(2)之所以说arguments是伪数组,是因为:arguments可以修改元素,但不能改变数组的长短。举例:

复制代码
    fn(2,4);
    fn(2,4,6);
    fn(2,4,6,8);

    function fn(a,b) {
        arguments[0] = 99;  //将实参的第一个数改为99
        arguments.push(8);  //此方法不通过,因为无法增加元素
    }
复制代码

清空数组的几种方式:

   var array = [1,2,3,4,5,6];

    array.splice(0);      //方式1:删除数组中所有项目
    array.length = 0;     //方式1:length属性可以赋值,在其它语言中length是只读
    array = [];           //方式3:推荐

 案列:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script type="text/javascript">
         //声明函数
        function add(x,y){
            alert(x+y);
            return x+y;
        };
        var sum = add(1,2);
        console.log(sum);

        //普通函数
         function add() {
             // body...
             console.log(arguments);
             // arguments它不是一个数组 伪数组 它有数组的索引和length
             console.log(arguments);
         }
         add('alex','wusir')

        // 函数对象
        var add = function() {
            alert(111);
            return 1;
        };
        console.log(typeof add);
        console.log(add());
        console.log(add);
</script>
</head>
<body>
<h1>
    alex
</h1>
</body>
</html>

 

 


posted @ 2019-09-14 22:14  奋斗的小孩_小小鸟  阅读(99)  评论(0)    收藏  举报