Array destructuring syntax provides a quick way to assign elements of an array to multiple variables in a single line.
let array = [1,2,3,4];
let [ a, b, ...c ] = array;
echo a // "1"
echo b // "2"
echo c // "3 4"
let d = 0
let e = 0
[ d, e ] = c
echo d // 3
echo e // 4
Amber could support:
Individual assignment. The number of variables to unpack and the length of the array need not be the same.
let [ a, b ] = array;
echo a // "1"
echo b // "2"
However, there is the question of what to do when there are more variables than elements in the array.
let array = [1];
let [ a, b ] = array;
echo b // ??
Ignore array elements. Individual elements in the array can be skipped or ignored when assigning to variables.
let [ , a ] = array; // or [ _, a ]
echo a // "2"
Trailing spread operator. Assign the remaining subarray into a variable.
let [ a, ...b ] = array;
echo a // "1"
echo b // "2 3 4"
This feature should perhaps be deferred to a later version as the presence of the spread operator here can lead people to believe that the spread operator can be used elsewhere like in array construction.
let arr_A = [1,2]
let arr_B = [...arr_A, 3]
echo arr_B // "1 2 3"
This Gist by JTBrinkmann demonstrates how a destructuring function could be implemented. However, each implementation involves globally declaring variables which would be troublesome when used inside a function.
Array destructuring syntax provides a quick way to assign elements of an array to multiple variables in a single line.
Amber could support:
Individual assignment. The number of variables to unpack and the length of the array need not be the same.
However, there is the question of what to do when there are more variables than elements in the array.
Ignore array elements. Individual elements in the array can be skipped or ignored when assigning to variables.
Trailing spread operator. Assign the remaining subarray into a variable.
This feature should perhaps be deferred to a later version as the presence of the spread operator here can lead people to believe that the spread operator can be used elsewhere like in array construction.
This Gist by JTBrinkmann demonstrates how a destructuring function could be implemented. However, each implementation involves globally declaring variables which would be troublesome when used inside a function.