The [series for ES6 -03] ES6 Explanation about the parameters relevant characteristics (the default value of the parameter and the remaining parameters destructuring assignment)

[Original] code road workers

Hello everyone, here is the code the road workers have the power, I am yards road worker, you are the power.


Today summarize ES6 with content related parameters.
Welcome to add treatise, message exchange.
Let us learn from each other and progress together.

  • 1. ES6 parameter default values ​​(parameter nonessential / optional)

    Before ES6, function parameters are not set default values, smart people, of course there are alternative ways to participate by judging began to give it conferred on the expected initial value function just. In particular are described in this.

    Reading: [Manual Default parameter values ​​ES5 implemented] [ES5Parameter]

    To the ES6, you can happily set the default value of the parameter. In the following defaultParamInEndfunctions, with age = 18to set the default value.

    /* eg.0
    * set default value for parameters
    */
    //-------------------------------------------------
    
    const defaultParamInEnd = function(name, age = 18) {
        console.log(`name: ${name} -- age: ${age}`)
    }
    
    defaultParamInEnd("Coder Power")
    // name: Coder Power -- age: 18
    
    defaultParamInEnd("Coder Power", 32)
    // name: Coder Power -- age: 32
    
    //-------------------------------------------------

    In the example above, the default value is set in the end, we are CSharper a conventional manner, when a plurality of parameters have default values ​​is continuously placed at the end.

    C# Parameter setting default values ​​are not allowed in the middle or discontinuous, optional parameters must be placed behind all the required parameters.

    That jsthe Can, parameters with default values (ie, non-mandatory parameters), not in the last place? The following example, we try.

```javascript
/* eg.1
* default value of parameters
*/
//-------------------------------------------------

const defaultParamInCenter = function(name, age = 18, gender) {
    console.log(` name: ${name} -- age: ${age} -- gender: ${gender}`)
}

defaultParamInCenter("Coder Power", undefined, "male")
// name: Coder Power -- age: 18 -- gender: male

defaultParamInCenter("Coder Power", null, "male")
// name: Coder Power -- age: null -- gender: male

//-------------------------------------------------
```

结果显示,非必需参数可以出现在中间位置(后面再跟有必需参数)。

注意在传值上还有以下区别:

- 当我们给带默认值的形参`age`传一个`undefined`的时候,函数里得到了默认值`18`;

- 而当我们传`null`的时候,函数里就没有得到默认值,而是`null`了。

建议在定义函数时还是将非必需参数写在最后,设默认值本身就是为了调用时方便,这样就不必为了凑数去传一个`undefined`,直接不传才是非必须参数设计的初衷。
  • 2. The remaining syntax operator acquires remaining parameters (Rest operator syntax)...

    ( ...Both 剩余操作符语法is 展开操作符语法Spread operator syntax, the other made an introductory)

    /* eg.2
    * rest parameters
    */
    //-------------------------------------------------
    
    function restParams(name, ...other) {
        console.log(`name: ${name}`)
        console.log(`other: ${other}`)
    }
    
    restParams("Coder Power", 18, "male")
    // name: Coder Power
    // other: 18,male
    
    //-------------------------------------------------

    From the above information in print other: 18,malecan be seen, otherput the two values, that is, the value of the remaining two parameters have been received of its own.

    If no remaining operator parameter syntax, it can receive only a positive or value (i.e. the value of the second parameter). Road workers believe this code can be understood:

    ...First, it will came back parameters collected, equivalent to put [ ]the array, and then act as 展开操作符语法, the equivalent of doing a copy parameter stuffed otherinside.
    Or directly understood as to pass over the remaining parameters 展开操作符语法stuffed parameter otherli.

    • Brain cave about: Expand operator syntax can not do at the end of the argument?
      JavaScript `` `
      / * eg.3
      • rest parameter operator not in end
        */
        //-------------------------------------------------

      function restParamsNotInEnd(...someParams, gender) {
      console.log(other: ${other})
      console.log(someParams: ${someParams})
      }

      restParamsNotInEnd("Coder Power", 18, "male")
      // SyntaxError: Rest parameter must be last formal parameter

      // ------------------------------------------------ -
      `` 结果报错了,异常信息显示remaining parameters must be placed in the last position '.

  • 3. deconstruction assigned parameter (Destructuring Assignment)

    If a simple method for processing content merely uses the individual properties of an object, and received parameter is a complete object, deconstruction can only get the desired content (or may be all the attributes).

    /* eg.4
    * Destructuring Assignment of parameters
    */
    //-------------------------------------------------
    
    const person = {
        name: "Coder Power",
        age: 18,
        gender: "male",
        mail: "[email protected]",
        sister: [
            {
                name: 'Emily',
                age: 22,
                gender: "female"
            },
            {
                name: 'Lucy',
                age: 15,
                gender: "female"
            }
        ],
        address: "avenue city province country"
    }
    
    function sayHello ({ name, age, birthday = 20101219 }) {
        console.log(`Hello! I'am ${ name }, ${ age } years old.`)
    }
    
    sayHello(person)
    // Hello! I'am Coder Power, 18 years old.
    
    //-------------------------------------------------
    In fact { }deconstruction not only can be used in parameters, written in the function is the same effect.
    The same is also reflected in the back to be mentioned modular 导入 importon use.
    note:
    • Parameters in the deconstruction of the assignment does not support alias, the deconstruction other support aliases
    • But you can assign default values

      /* eg.4
      * default value for Destructuring Assignment of parameters
      */
      //-------------------------------------------------
      
      function sayHelloAgain ({ name, age, birthday = 19860101 }) {
          console.log(`Hello! I'am ${ name }, ${ age } years old.`)
          console.log(`Birthday: ${ birthday}`)
      }
      
      sayHelloAgain(person)
      // Hello! I'am Coder Power, 18 years old.
      // Birthday: 19860101
      
      //-------------------------------------------------

      Above example prints the birthdaydefault values.


ES6 content on the parameters related to the introduction here, which has not been mentioned characteristics used, will be introduced one by one in a subsequent article.

Welcome falsehood and forwarding treatise share. Comments area may also leave a message before you go ah ~

I hope you can help, next goodbye.


Guess you like

Origin www.cnblogs.com/CoderMonkie/p/es6-function-parameter.html