Home > Web Front-end > JS Tutorial > How to use the function of destructuring assignment in ES6

How to use the function of destructuring assignment in ES6

php中世界最好的语言
Release: 2017-12-30 17:59:38
Original
1776 people have browsed it

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];
Copy after login


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();
Copy after login

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});
Copy after login

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]
Copy after login

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
};
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template