What I will bring to you this time is how to use the function of destructuring assignment in ES6. There are a total of 4 methods. This article will give you a good analysis.
Exchange the values of variables
[x, y] = [y, x];
The above code exchanges the values of variables x and y. This writing method is not only concise, but also easy to read, and the semantics are very clear.
Returning multiple values from the function
The function can only return one value. If you want to return multiple values, you can only return them in an array or object. With destructuring assignments, it is very convenient to retrieve these values.
// 返回一个数组 function example() { return [1, 2, 3]; } var [a, b, c] = example(); // 返回一个对象 function example() { return { foo: 1, bar: 2 }; } var { foo, bar } = example();
Definition of function parameters
Destructuring assignment can easily correspond a set of parameters to variable names.
// 参数是一组有次序的值 function f([x, y, z]) { ... } f([1, 2, 3]); // 参数是一组无次序的值 function f({x, y, z}) { ... } f({z: 3, y: 2, x: 1});
Destructuring assignment is particularly useful for extracting data from JSON objects.
var jsonData = { id: 42, status: "OK", data: [867, 5309] }; let { id, status, data: number } = jsonData; console.log(id, status, number); // 42, "OK", [867, 5309]
The above code can quickly extract the value of JSON data.
jQuery.ajax = function (url, { async = true, beforeSend = function () {}, cache = true, complete = function () {}, crossDomain = false, global = true, // ... more config }) { // ... do stuff };
I believe you have mastered the method after reading the above introduction. For more exciting information, please pay attention to other related articles on the php Chinese website!
Related reading:
The solution for max-width and min-height not being supported by IE6
##Use memcached, Implementation steps of xcache for PHP cache optimization
How to implement asynchronous synchronous requests in AJAX use
The above is the detailed content of How to use the function of destructuring assignment in ES6. For more information, please follow other related articles on the PHP Chinese website!