JavaScript 中的解构赋值模式似乎并不清晰

A destructuring assignment pattern doesn't seem clear in JavaScript

来自网站exploringjs

Before ES6, there was no corresponding mechanism for extracting data. That’s what destructuring is – it lets you extract multiple properties from an object via an object pattern. For example, on the left-hand side of an assignment:

const { first: f, last: l } = obj;

我理解下面的示例,例如,将 http 模块中的 createServer 方法分配给同名变量。

const { createServer } = require('http');

但是这个呢:

const { parse: parseUrl } = require('url');

如何在代码中使用它?

当您想要更改来自 require('url')

的变量的名称时,您可以使用它

因为 require('url') 包含 parse 但可以说你在当前范围内已经有名为 parse 的变量并且你想从 require('url') 在这种情况下,您使用此模式将其重命名为 parseUrl

示例:

const parse = "some value";
const { parse: parseUrl }  = require('url');
console.log(parse); // "some value";
console.log(parseUrl); // value coming from require('url');

它只是提取 parse 数据并在此范围内创建一个 parseUrl 变量。

当(假设)您使用 API 并希望使用变量而不是成员访问时,这会非常方便:

const {id: serviceID} = await fetchDefaultService();
const {id: uid} = await fetchUser(serviceID, uid);

它只是让您可以控制命名(parseUrlparse 更有意义)并让您避免潜在的冲突。

您示例中的行从 url 模块中剥离了 parse 函数,并将其重命名为 parseUrl。你可以这样使用它:

> const { parse: parseUrl } = require('url')
undefined
> parseUrl('http://whosebug.com/')
Url {
  protocol: 'http:',
  slashes: true,
  auth: null,
  host: 'whosebug.com',
  port: null,
  hostname: 'whosebug.com',
  hash: null,
  search: null,
  query: null,
  pathname: '/',
  path: '/',
  href: 'http://whosebug.com/' }

这只是来自 node 回复的 copy/pasted。打开你的终端,然后输入命令 node,你可以交互式地输入 js 并测试会发生什么。

解构是一项很棒的功能,可以帮助您非常轻松地从数组中提取对象属性或元素 让我们通过例子来理解它

  • 在第一个示例中,因为 obj 有一个名为 name 的属性,我们可以从中提取它
  • 所以如果对象有道具我们可以提取它。

    let obj = {
      name :'maged' 
    }
    let {name} = obj ;  // have this prop 
    let {fullName} = obj ; // don't have this prop 
    console.log(name) ; // maged  
    console.log(fullName) ;  // undefined 
    

    • 在这个例子中,我们 return 一个函数的对象,该函数类似于 nodejs 中的 require 函数 return 导出对象

function require(module) {
  return {
      name : module ,
      method1: '1' ,
      method2 : '2'
   }
}
let obj =  require('url') ; 
let {name,method1,method2} = obj ; 
console.log(name) ; // url 
console.log(method1) ; // 1 
console.log(method2) ;  // 2 

  • 如您所见,我们可以如此轻松地从 returned 对象中提取多个属性

  • 在我们的第三个例子中,我们将看到如何将 prop 提取到一个新的变量名

  • +

let obj = {
  a :'a' ,
  b:'b' 
}
let {a:first , b:second} = obj ;
console.log(first) ; // a 
console.log(second) // b
console.log(a); // Uncaught ReferenceError: a is not defined 

如您所见,我们将属性提取为新变量名,这很棒,

  • 现在到最后一个例子,我们将看到如果变量不存在于对象中,如何为变量分配默认值,这对于传递给函数时的默认对象属性等有好处,

let obj = {
  fullName : 'Sniper' 
}
let {fullName='super'} = obj ; // sniper from the obj 
console.log(fullName) ; 
let {name='maged'} = obj ; // maged because undefined in the obj 
console.log(name) ;

我希望这些示例能以某种方式帮助您理解解构及其工作原理

Note Destructuring works with arrays