zoukankan      html  css  js  c++  java
  • es6中参数【默认值,扩展运算符】

    • 参数默认值

    1、普通参数

    function info(age,name="grace"){
        console.log(name);
    }
    info(); //输入:grace
    

    2、对象参数【参数为对象时,不输入任何参数,需要进行处理】

    //Handling named parameters【tip:参数name与传递进来的对象中的属性名name需要一一对应】
    function selectEntries({ name=0, end=-1, step=1 }) {
        console.log(name);
    }
    selectEntries({name:"Jane"});//结果:Jane
    
    //selectEntries();//error: Cannot match against 'undefined' or 'null'.针对这一问题给出下面函数的处理方案
    
    function selectEntries2({ name="lea", end=-1, step=1 }={}) {
        console.log(name);
    }
    selectEntries2();//结果:lea
    • 扩展运算符

    1、基本用法【函数传参】

    //2、From arguments to rest parameters【...】
    function allArgs(...args) {
        console.log(...args);//结果:2,3,4,5
        console.log(args);//结果数组:[2,3,4,5]
        for (const arg of args) {
            console.log(arg);
        }
    }
    allArgs(2,3,4,5);
    

    2、Math中的应用

    //【func.call(obj,arg1,arg2,......]】【上面是为了检测数组中最大的值,所以用apply,此处的call仅用于巩固】
    const max1 = Math.max.call(null,-1,5,11,3);
    console.log(max1); //结果:11
    //es5【func.apply(obj,[arg1,arg2,......]】
    const max = Math.max.apply(null, [-1, 5, 11, 3]);
    console.log(max); //结果:11
    //es6
    const max2 = Math.max(...[-1, 5, 11, 3]);
    console.log(max2); //结果:11
    

    3、数组的push

    //向一个数组添加一个数组的数据【改变原数组】
    let arr = ['lea'];
    arr.push('joa','pia');//添加单个值
    console.log(arr);//结果:[ 'lea', 'joa', 'pia' ]
    //es5
    arr.push.apply(arr,['a','b']);//通过数组添加
    console.log(arr);//结果:[ 'lea', 'joa', 'pia', 'a', 'b' ]
    
    //es6
    arr.push(...['a','b']);//将数组解析为多个值
    console.log(arr);//结果:[ 'lea', 'joa', 'pia', 'a', 'b', 'a', 'b' ]
    

    4、合并数组

    //合并数组
    let arr = ['lea'];
    //es5 concat,【返回新的数组,不影响原数组】
    console.log(arr.concat([2,4]));//结果:[ 'lea', 2, 4 ]
    
    //es6
    console.log([...arr,...['cd']]);//结果:[ 'lea', 'cd' ]
  • 相关阅读:
    octotree神器 For Github and GitLab 火狐插件
    实用篇如何使用github(本地、远程)满足基本需求
    PPA(Personal Package Archives)简介、兴起、使用
    Sourse Insight使用过程中的常使用功能简介
    Sourse Insight使用教程及常见的问题解决办法
    github 遇到Permanently added the RSA host key for IP address '192.30.252.128' to the list of known hosts问题解决
    二叉查找树的C语言实现(一)
    初识内核链表
    container_of 和 offsetof 宏详解
    用双向链表实现一个栈
  • 原文地址:https://www.cnblogs.com/lee90/p/8631981.html
Copyright © 2011-2022 走看看