Destructuring assignment and its principles

Destructuring assignment (Destructuring Assignment) is a technique in programming languages ​​that breaks down complex data structures (such as arrays and objects) into smaller parts and assigns them to variables. It has support in many programming languages, including JavaScript.

Destructuring assignment in JavaScript allows you to extract values ​​from an array or object and assign those values ​​to variables, making it easier to access and work with the data. The following are some basic uses and principles of destructuring assignment:

1. Array destructuring and assignment:

const [a, b] = [1, 2];
console.log(a); // 输出 1
console.log(b); // 输出 2

In the above example, we [1, 2]deconstructed the values 1​​and from the array 2and assigned them to the variables aand respectively b.

2. Object destructuring and assignment:

const { x, y } = { x: 1, y: 2 };
console.log(x); // 输出 1
console.log(y); // 输出 2

In this example, we { x: 1, y: 2 }deconstruct the values ​​of attributes xand from the object yand assign them to the variables xand respectively y.

3. Default value: You can also specify a default value for the variable assigned by destructuring to handle attributes or elements that may not exist.

const { a = 1, b = 2 } = { a: 3 };
console.log(a); // 输出 3
console.log(b); // 输出 2
  1. In this example, since there are no bproperties in the object, bthe value of the variable is set to its default value 2.

The principle of destructuring assignment is to match the value on the right based on the pattern on the left and assign the matching value to the corresponding variable. It works on arrays and objects, can be nested, and can also be used in function parameters.

It should be noted that destructuring assignment is a kind of syntactic sugar. It actually calls the object's Symbol.iteratormethod (for arrays) or Symbol.iteratoror Symbol.unscopablesmethod (for objects), and then assigns the value to the variable according to the matching rules. This process is performed automatically in the background, making destructuring assignment very convenient and flexible. Therefore, destructuring assignment is a powerful tool for simplifying code and improving code readability.

Guess you like

Origin blog.csdn.net/m0_74801194/article/details/132847513