Destructuring assignment

Destructuring assignment

Destructuring assignment

Function

Destructuring assignment is used to take out multiple values from array or object at one time and assign them to variables. The left side uses tuple-like parentheses, but BT currently does not provide an independent tuple type, and the value on the right side still maintains the original array or object type.

Syntax

Space separation and comma separation are equivalent, and can also be mixed:

Parameters

  • Left-hand variables: A list of variable names in brackets. The first version only supports ordinary variable names.
  • Right side value: must be array or object.

Return Value

The return value of the destructuring assignment expression is the value on the right side, which is consistent with the ordinary assignment expression.

Array destructuring reads in subscript order. When the number of variables is less than the length of the array, the extra elements will be ignored; when the number of variables is more than the length of the array, the missing position is assigned the value empty.

Object destructuring reads the field with the same name of the object according to the variable name on the left. When the field does not exist, the corresponding variable is assigned the value empty.

Code Examples

Array destructuring:

Object destructuring:

Single field object destructuring will maintain reference semantics:

The assignment expression returns the right-hand value:

For loop destructuring the current value:

Loop destructuring only acts on the value obtained in each iteration and does not change the semantics of ordinary for key,value in users.

Notes

is not array or object, a runtime error will occur:

Error message: