zoukankan      html  css  js  c++  java
  • js函数中写默认值的几种方式(常见的)

    <script>
    <!--第一种写法,我更喜欢第一种写法直观一些-->
    function Person(name){
    this.name = name || '默认名字乔丹';
    }
    var person = new Person('詹姆斯01');//this-->person
    console.log(person.name,'看啥名字')//詹姆斯01,如果不传递参数或者传递的参数为假(比如'',null)---就是默认的乔丹
    <!--第2种写法-->
    function Person1(name){
    console.log(arguments,'我是arguments')
    this.name = arguments[0] ? arguments[0] : '默认的名字02'
    }
    console.log(new Person1(''));

    // 区别就是里面一个用|| 一个用三元,这里又可以了解一个只是点了 arguments
    //第三种方法,这种方法适合用于参数较多的情况,使用了Jquery的扩展:这个我就不写了 很少用到jq了

     




    </script>
    https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Functions/arguments 链接Arguments的

    arguments 是一个对应于传递给函数的参数的类数组对象。
    arguments对象是所有(非箭头)函数中都可用的局部变量。你可以使用arguments对象在函数中引用函数的参数。
    arguments对象不是一个 Array 。它类似于Array,但除了length属性和索引元素之外没有任何Array属性
    但是它可以被转换为一个真正的Array

    您还可以使用Array.from()方法或扩展运算符将参数转换为真实数组:

    Array.from专程数组
    console.log(Array.from(arguments),'我是arguments对象,专程数组')
    console.log([...arguments],'我是arguments对象,专程数组')

    总结一下 arguments的三点用法:
    @1 一、实现重载(类似循环)

    二、同数组下标访问实参(这个比较常规)

    三、属性callee指向自己(没怎么用过或者见过)

    callee就是它的方法,这个方法用的不多,很容易被我们忽略,它指向的是正在被执行的Function对象,最常用的例子就是用来做递归了。




     


  • 相关阅读:
    670. Maximum Swap
    126. Word Ladder II
    695. Max Area of Island
    689. Maximum Sum of 3 Non-Overlapping Subarrays
    667. Beautiful Arrangement II
    前端开发-css
    前端开发-html
    mysql补充
    pythonl操作数据库
    mysql索引原理
  • 原文地址:https://www.cnblogs.com/myfirstboke/p/10438890.html
Copyright © 2011-2022 走看看