ES6-string, numeric, boolean and function parameter destructuring assignment
- Deconstruction and assignment of strings The
reason why a string can be deconstructed is because the string is converted into an array-like object
let [a, b, c, d, e] = 'Jisoo';
console.log(a); //J
console.log(b); //i
console.log(c); //s
console.log(d); //o
console.log(e); //o
The class array has a length attribute, so this attribute can also be deconstructed and assigned
let {
length: len
} = 'jisoo';
console.log(len);//5
- Destructuring assignment of numeric and boolean values
If the right side of the equal sign is numeric or boolean, it will be converted to an object first
let {
prop: x
} = 123;
console.log(x); //undefined(123被转换为对象)
let {
prop1: y
} = true;
console.log(y); //undefined(true被转换为对象)
let {
prop2: z
} = undefined;//undefined不能转换为对象,所以报错
console.log(z); //Error
- Destructuring assignment of function parameters
function add([x, y]) {
return x + y;
}
var sum = add([1, 2]);
console.log(sum);
The function add() parameter surface is an array, but in fact, at the moment when the parameter is passed in, the array parameter is deconstructed into the variable x and y
. The deconstruction of the function parameter can also use the default value
function move({
x = 0,
y = 0
} = {}) {
return [x, y];
}
var x = move({
x: 3,
y: 8
});
console.log(x); //[3,8]
var y = move({
x: 3
});
console.log(y); //[3,0]
var z = move({}); //
console.log(z); //[0,0]