zoukankan      html  css  js  c++  java
  • arguments对象

    arguments对象是所有函数中可用的局部变量。你可以使用arguments对象在函数中引用函数的参数。此对象包含传递给函数的每个参数的条目,第一个条目的索引从0开始。arguments对象仅在函数内部有效,在函数外部调用会出现一个错误。

    arguments的属性:

    arguments.callee:指向当前执行的函数

    arguments.caller:指向调用当前函数的函数

    arguments.length:指向传递给当前函数的参数数量

    1.使用arguments对象,无需明确指出参数名

    function sayHi(){
       if(arguments[0] === "bye"){
          return;
       }  
       alert(arguments[0])  
    } //第一个参数用arguments[0],第二个参数用arguments[1]以此类推

    2.检测参数个数,arguments类似一个数组,但它除了长度之外没有任何数组属性

    function howManyArgs(){
      alert(arguments.length);
    }
    howManyArgs('string',45)  //2
    howManyArgs();//0
    howManyArgs(12) // 1

    3.将arguments转换成一个真正数组

    let  args = Array.prototype.slice.call(arguments);
    
    let args = [].slice.call(arguments)
    
    let args = Array.from(arguments)
    
    let args =  [...arguments]

    4.模拟函数重载

    function doAdd(){
       if(arguments.length === 1){
          alert(arguments[0]+5);
       }  else if(arguments.length === 2){
          alert(arguments[0] + arguments[1])
       }
    }
    
    doAdd(10)  //15
    
    doAdd(40,20)  //60

    5.arguments的typeof返回'object'

    console.log(typeof arguments)  // object

    console.log(typeof arguments[0]) // 返回单个参数的typeof

  • 相关阅读:
    博客园设置自定义页面[布局][样式]
    linux的hostname文件目录
    mybatis底层源码分析之--配置文件读取和解析
    Enum的使用
    easyUI datagrid笔记
    软工实践第二次作业-黄紫仪
    软工实践第一次作业-黄紫仪
    第五次作业--原型设计
    作业三
    作业二
  • 原文地址:https://www.cnblogs.com/cxdxm/p/7304925.html
Copyright © 2011-2022 走看看