Indefinite arguments and the spread operator in JavaScript

1. Indicates: .... (three dots)

2. Usage

  1. Used in formal parameters, it means passing to other parameter sets, similar to arguments, called indefinite parameters, grammatical format: add three dots (...) in front of formal parameters
  2. Used in front of an array, you can break up and expand all the values ​​​​of the array, called the expansion operator, syntax format: add three dots (...) in front of the array

3. Specific instructions

To find the sum of indeterminate parameters, you can use arguments before, but now you can use indefinite parameters to do it, as follows:

        function add(...values) {
            console.log(values)//[10, 20, 25]
            let sum = 0
            for (let i = 0; i < values.length; i++) {
                sum += values[i]
            }
            return sum
        }
        var res=add(10,20,25)
        console.log(res)//55

But it should be noted that the indefinite parameter can only be placed later, and there can only be one indeterminate parameter in the function:

        function add(...values,a) {  }//报错
        function add(...value1,...value2)//报错

Guess you like

Origin blog.csdn.net/weixin_46872121/article/details/123257742