2. Deconstruction assignment of objects
Keywords:
Front-end
Attribute
Javascript
Object deconstruction assignment
Brief introduction
- The elements of an array are arranged in order, and the value of a variable is determined by its position; while the attributes of an object are not in order, the variables must have the same name as the attributes in order to get the correct value.
- If the deconstruction fails, the value of the variable is equal to undefined
- The rule of deconstruction assignment is that as long as the value on the right side of the equals sign is not an object or an array, it is first converted to an object. Because undefined and null cannot be converted to objects, an error will be reported when they are deconstructed and assigned.
let { bar, foo } = { foo: 'aaa', bar: 'bbb' };
foo
bar
---------------------------------------------------
let { baz } = { foo: 'aaa', bar: 'bbb' };
baz
The method of assigning an object to a variable
const { log } = console;
log('hello')
Attribute and variable and object deconstruction assignment of es6 extension
- The internal mechanism of object deconstruction assignment is to find the same name attribute first, and then assign the corresponding variables. It is the latter, not the former, that is really assigned.
let { foo: baz } = { foo: 'aaa', bar: 'bbb' };
baz
let { foo: foo } = { foo: 'aaa', bar: 'bbb' };
foo
Traversal assignment of a variable three times
const node = {
loc: {
start: {
line: 1,
column: 5
}
}
};
let { loc, loc: { start }, loc: { start: { line }} } = node;
line
loc
start
Objects have the same default value as arrays
var {x = 3} = {};
x
------------------------------------------------------
var {x, y = 5} = {x: 1};
x
y
------------------------------------------------------
var {x: y = 3} = {x: 5};
y
------------------------------------------------------
var { message: msg = 'Something went wrong' } = {};
msg
------------------------------------------------------
var {x = 3} = {x: null};
x
Attention Points of Object Deconstruction Assignment
let x;
{x} = {x: 1};
let x;
({x} = {x: 1});
Deconstruction of Object Attributes for Arrays
let arr = [1, 2, 3];
let {0 : first, [arr.length - 1] : last} = arr;
first
last
Posted by DaveM on Sat, 12 Oct 2019 07:50:38 -0700