In-depth Understanding of ES6 005 [Study Notes]

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:
// Syntax error `var {tyep,name}`
// Syntax error `let {type,name}`
// Syntax error `const {type,name}`
To assign values to already declared variables using destructuring, consider the following:
`let node = { type:&qu...`

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

(0)
Walker的头像Walker
上一篇 Mar 8, 2025 12:51
下一篇 Mar 8, 2025 12:39

Related Posts

  • In-depth Understanding of ES6 001 [Study Notes]

    Block-Level Scope Binding
    Previously, `var` variable declarations, regardless of where they were declared, were considered to be declared at the top of their scope. Since functions are first-class citizens, the typical order was `function functionName()`, followed by `var variable`.

    Block-Level Declarations
    Block-level declarations are used to declare variables that cannot be accessed outside the scope of a specified block. Block-level scope exists in:
    - Inside functions
    - Within blocks (the region between `{` and `}`)

    Temporal Dead Zone
    When the JavaScript engine scans code and finds variable declarations, it either hoists them to the top of the scope...

    Personal Mar 8, 2025
    1.6K00
  • From 0 to 1: Implementing Micro-frontend Architecture 001 [Study Notes]

    Micro-frontends, JS isolation, CSS isolation, element isolation, lifecycle, preloading, data communication, application navigation, multi-level nesting. Note: This uses Mermaid's flowchart syntax, which is supported by Markdown renderers such as Typora, VitePress, and some Git platforms. Retained: Host application main-vue3; child applications: child-nuxt2-home, child-vue2-job, child-vu...

    Apr 20, 2025
    1.5K00
  • Go Engineer Comprehensive Course: Protobuf Guide [Study Notes]

    Protocol Buffers Getting Started Guide 1. Introduction Protocol Buffers (protobuf for short) is a language-agnostic, platform-agnostic, extensible structured data serialization mechanism developed by Google. Compared with serialization methods such as JSON and XML, protobuf is smaller, faster, and simpler. Project homepage: https://github.com/protocolbuffers/prot…

    Personal Nov 25, 2025
    1.2K00
  • In-depth Understanding of ES6 011 [Learning Notes]

    Promises and Asynchronous Programming

    Because the execution engine is single-threaded, it needs to track the code that is about to run. This code is placed in a task queue. Whenever a piece of code is ready to execute, it is added to the task queue, and whenever a piece of code in the engine finishes execution, the event loop executes the next task in the queue. A Promise acts as a placeholder for the result of an asynchronous operation. It doesn't subscribe to an event or pass a callback function to the target function. Instead, it allows the function to return a Promise, like this...

    Personal Mar 8, 2025
    1.1K00
  • In-depth Understanding of ES6 008 [Study Notes]

    Iterators (Iterator) and Generators (Generator) are new features indispensable for efficient data processing. You will also find iterators present in other language features: the new for-of loop, the spread operator (...), and even asynchronous programming can use iterators. An iterator is a special object that has proprietary interfaces specifically designed for the iteration process. All iterator objects have a next() method, and each call returns a result pair...

    Personal Mar 8, 2025
    1.1K00
EN
简体中文 繁體中文 English
欢迎🌹 Coding never stops, keep learning! 💡💻 光临🌹