Destructuring: Making Data Access More Convenient
If you declare variables using `var`, `let`, or `const` with destructuring, you must provide an initializer (i.e., the value on the right side of the equals sign). The following will cause an error:
// 语法错误
var {tyep,name}
// 语法错误
let {type,name}
// 语法错误
const {type,name}
To assign values to already declared variables using destructuring, see below:
let node = {
type:"Identifier",
name:"foo"
},
type = "Literal",
name = 5;
// 使用解构语法为多个变量赋值 ,请注意一定要使用小括号包裹解构赋值的方法(js引擎将一对开放的花括号视为一个代码块,而语法规定,代码块语句不允许出现在赋值语句侧,添加小括号后可以将语句转化为一个表达式
({type,name}=node)
console.log(type) // Identifier
console.log(name) // foo
The value of a destructuring assignment expression is equal to the value on the right side of the expression (i.e., the right side of `=`). This means you can use a destructuring assignment expression anywhere a value is expected, as follows:
let node = {
type:"Identifier",
name:"foo"
},
type = "Literal",
name = 5;
function outputinfo(value){
console.log(value===node); // true
}
outputinfo({type,name} = node);
console.log(type) // "Identifier"
console.log(name) // "foo"
// The value of the expression is the value on the right side. This syntax means `value` is passed `node`, and `type` and `name` are assigned.
// When calling the `outputInfo()` function, a destructuring expression is passed. Since the value of a JavaScript expression is the value on its right side, the parameter passed here is equivalent to `node`, and the variables `type` and `name` are reassigned. Finally, `node` is passed to the `outputInfo()` function.
If a destructuring assignment expression (i.e., the expression on the right side of `=`) is `null` or `undefined`, it will cause the program to throw an error. Any attempt to read properties of `null` or `undefined` will trigger a runtime error.
Default Values
When using a destructuring assignment expression, if the specified local variable name does not exist in the object, that local variable will be assigned `undefined`.
let node = {
type:"Identifier",
name:"foo"
}
let {type,name,value} = node;
console.log(type) //Identifier
console.log(name) // foo
console.log(value) // undefined
// Default values: When a specified property does not exist, you can define a default value by adding an equals sign (=) and the corresponding default value after the property name.
let node = {
type:"Identifier",
name:"foo"
}
let {type,name,value=true} = node; // This value only takes effect if the property does not exist on `node` or its value is `undefined`.
console.log(type) //Identifier
console.log(name) // foo
console.log(value) // true
Assigning to Local Variables with Different Names
Destructuring assignments typically use local variables with the same names as the object properties. For example, the value of `node.type` is stored in the `type` variable. However, if you want to use differently named local variables to store object property values,
let node = {
type:"Identifier",
name:"foo"
}
let {type:localType,name:localName="bar"} = node;
console.log(type) //Identifier
console.log(name) // foo
// Differently named local variables, with default values
let node = {
type:"Identifier"
}
let {type:localType,name:localName="bar"} = node;
console.log(type) //Identifier
console.log(name) // bar
Nested Object Destructuring
Destructuring nested objects is still similar to object literal syntax; you can deconstruct objects to get the information you want.
let node = {
type:"Identifier",
name:"foo",
loc:{
start:{
line:1,
column:1
},
end:{
line:1,
column:4
}
}
}
let {loc:{start}} = node;
console.log(start.line); // 1
console.log(start.column); // 1
// Using differently named local variables
let node = {
type:"Identifier",
name:"foo",
loc:{
start:{
line:1,
column:1
},
end:{
line:1,
column:4
}
}
}
let {loc:{start:localStart}} = node;
console.log(localStart.line); // 1
console.log(localStart.column); // 1
In the following statement, because there is only a pair of curly braces on the right side, it will not declare any bindings. `loc` is not a binding to be created; it represents the position where properties are retrieved within the object.
// 未声明任何变量!
let {loc:{}} = node
Array Destructuring
Compared to object destructuring syntax, array destructuring is much simpler. It uses array literals, and all destructuring operations are performed within the array, rather than using objects like object literal syntax.
let colors = ["red","green","blue"]
let [firstColor,secondColor]=colors
console.log(firstColor) //red
console.log(firstColor) // green
// Provide variables only for elements of interest. Remember, the array itself does not change during this process.
let [,,thirdColor] = colors;
console.log(thirdColor) // blue
Array Destructuring Assignment
In the context of array destructuring assignment, there is no need to wrap the expression in parentheses.
These syntaxes for array destructuring assignment are sufficient. Array destructuring syntax also has a unique use case: variable swapping.
If the right-hand side of an array destructuring assignment expression is `null` or `undefined`, it will cause the program to throw an error. This characteristic is very similar to object destructuring values.
let a = 1, b = 2;
[a,b] = [b,a];
console.log(a) // 2
console.log(b) // 1
Nested Array Destructuring
let colors = ["red",["green","lightgreen"],"blue"];
//
let [firstColor,[secondColor]] = colors;
console.log(firstColor); // red
console.log(secondColor); // green
Rest Elements
You can assign the remaining elements in an array to a specific variable using the `...` syntax.
let colors = ["red","green","blue"]
let [firstColor,...restColors] = colors;
console.log(firstColor) // "red"
console.log(restColors[0]); // green
console.log(restColors[1]); // blue
ES5 often uses the `concat()` method to clone arrays; if called without arguments, it returns a copy of the current array. ES6 can achieve the same goal through the rest elements syntax.
// es5
var colors = ["red","green","blue"];
var clonedColors = colors.concat();
console.log(clonedColors) // [red,green,blue]
// es6
let colors = ["red","green","blue"];
let [...clonedColors] = colors;
console.log(clonedColors); // [red,green,blue]
In a destructured array, the rest element must be the last item; adding more commas after it will cause a syntax error. You can use object destructuring to create more complex expressions, allowing you to extract desired information from any data structure that mixes objects and arrays.
let node = {
type: "Identifier",
name: "foo",
loc: {
start: {
line: 1,
column: 4
},
end: {
line: 1,
column: 4
}
},
range: [0,3]
}
let {
loc:{start},
range:[startIndex]
}
console.log(start.line); // 1
console.log(start.column); // 1
console.log(startIndex); 0
Destructuring Parameters
When defining a JavaScript function that accepts many optional parameters, we typically create an options object and define the extra parameters as properties of this object.
- Destructuring parameters that must be passed
- Default values for destructuring parameters
function setCookie(name,value,{
source = false,
path = '/',
domain = 'example.com',
expires = new Date(Date.now()+360000*1000)
}){
// 设置cookie的代码
}
setCookie("type","js",{secure:true,expires:60000})
// There's a peculiar aspect to destructuring parameters: by default, if you call a function without providing the destructured parameter, it will throw an error. For example, if the third parameter is not passed, an error will occur.
// 程序报错!
setCookie("type","js");
// The third parameter is missing, and its value is `undefined`. Destructuring parameters are just a shorthand for applying destructuring declarations to function parameters. That is, if the right-hand side of a destructuring assignment expression is `null` or `undefined`, the program will throw an error. Similarly, if the `setCookie()` function is called without passing the third parameter, it will also cause the program to throw an error.
// A good practice is to provide the same default values for it.
const setCookieDefaults = {
secure:false,
path: "/",
domain: "example.com",
expires: new Date(Date.now()+360000000)
}
function setCookie(name,value,{
secure:false,
path: "/",
domain: "example.com",
expires: new Date(Date.now()+360000000)
}=setCookieDefaults) {
// ....
}
In both object and array destructuring, you can set default values for object properties or array elements whose values are `undefined`. The right-hand side of the assignment expression cannot be `null` or `undefined`, otherwise the program will throw an error. You can use `var`, `let`, or `const` to declare variables with destructuring, but according to syntax rules, an initializer must be specified.
主题测试文章,只做测试使用。发布者:Walker,转转请注明出处:https://walker-learn.xyz/archives/4331