Benefits of es6 destructuring function parameters

Destructuring not only allows us to quickly get the value we want, such as we want to get 2, 4 in the array

let arr=[1,2,3,4]
let [,arr2,,arr4]=arr
console.log(arr2,arr4)//2,4

Another example is that we want to get the value of age and sex in obj in the object

let obj={name:'lisi',age:12,height:175,sex:1}
let {age,sex}=obj
console.log(age,sex)//12,1

In fact, we change the position of age and sex in deconstruction without affecting the result.

let obj={name:'lisi',age:12,height:175,sex:1}
let {sex,age}=obj
console.log(age,sex)//12,1

Using these two points, the position is not affected and the required value can be deconstructed. Then it is very convenient to apply deconstruction to the parameters of the function, like jQuery's ajax, that's it. So when we encapsulate functions, if the parameters are compared and uncertain, we can use the form of destructuring function.
Here is a brief example;

  function ajax({method,url,dataType,data}){//预定有这么多个参数
          //做逻辑处理
        }
        fun({url:'http://12.0.0.1:7000/img',method:'get'})//调用函数时不用顾忌参数顺序和个数

Guess you like

Origin blog.csdn.net/weixin_44494811/article/details/103319903