首页 \ 问答 \ 在Javascript中解构赋值的好处[关闭](Benefits of destructuring assignments in Javascript [closed])

在Javascript中解构赋值的好处[关闭](Benefits of destructuring assignments in Javascript [closed])

我越来越多地遇到使用ES2015引入的解构赋值的代码,更常见的是我发现很难理解作者正在做什么。 我可以看到,在某些情况下,解构可能非常有用,但我的印象是它经常引入不必要的代码复杂性。

例如,MDN上的嵌套对象和数组解构示例使用此行来构造嵌套数组:

var { title: englishTitle, translations: [{ title: localeTitle }] } = metadata;

这样的优势在哪里,对我来说看起来更具可读性:

var englishTitle = metadata.title,
    localeTitle  = metadata.translations[0].title;

解构任务正在解决哪些问题?

何时使用它们何时不使用?


More and more often I come across code making use of the ES2015 introduced destructuring assignment and even more often I find it very hard to understand what the author is doing. I can see that destructuring can be very useful in some cases but I have the impression that it is often introducing unnecessary code complexity.

E.g. the Nested object and array destructuring example on MDN is using this line do destructure a nested array:

var { title: englishTitle, translations: [{ title: localeTitle }] } = metadata;

Where is the advantage over something like this, that looks a lot more readable to me:

var englishTitle = metadata.title,
    localeTitle  = metadata.translations[0].title;

What problems are being solved by destructuring assignments?

When to use them and when not to?


原文:https://stackoverflow.com/questions/36167290
更新时间:2020-02-12 09:53

最满意答案

好处是您不需要重复解构表达式。 当然,在你的例子中它几乎没有什么区别,因为你已经在metadata变量中得到了它。

但如果它是一个非常复杂的表达式,或其他东西,你可以保存一个额外的变量。 例如,比较此功能

function example(metadata) {
    var englishTitle = metadata.title,
        localeTitle  = metadata.translations[0].title;
    …; // use englishTitle and localeTitle
}

function example({title: englishTitle, translations: [{title: localeTitle}]}) {
    …; // use englishTitle and localeTitle
}

它变得更具说明性。

因为每个语法糖都是如此:仅在它使代码变甜的地方应用它。


The benefit is that you don't need to repeat the destructured expression. Granted, in your example it hardly makes a difference, as you've already got it neatly in that metadata variable.

But if it is a very complex expression, or something else, you could save an extra variable. For example, compare this function

function example(metadata) {
    var englishTitle = metadata.title,
        localeTitle  = metadata.translations[0].title;
    …; // use englishTitle and localeTitle
}

to

function example({title: englishTitle, translations: [{title: localeTitle}]}) {
    …; // use englishTitle and localeTitle
}

and it becomes more obvious how declarative it is.

As it is true for every syntactic sugar: apply it only where it sweetens your code.

2016-03-23

相关问答

更多

来自元组的JavaScript变量赋值(JavaScript Variable Assignments from Tuples)

你必须这样做丑陋的方式。 如果你真的想要这样的东西,你可以查看一下CoffeeScript ,它具有这样的功能,还有很多其他的功能,使它看起来更像是python(抱歉让它听起来像一个广告,但我真的很喜欢它)。 You have to do it the ugly way. If you really want something like this, you can check out CoffeeScript, which has that and a whole lot of other fe ...

JavaScript:当我使用带有解构的赋值时,为什么我会得到`undefined`?(JavaScript: Why I get `undefined` when I use an assignment with destructuring?)

根据MDN文档 ,结构的解构分配基于属性名称。 对于第二个赋值,由于您的对象没有属性name和age ,因此这些变量未定义。 如果要在分配变量时重命名属性,可以使用以下语法: foo = {color: 'red', result: true}; ({color: name, result: age} = foo); 这会将foo的color属性赋值给变量name ,将result属性赋值为age 。 According to the MDN docs, destructuring assign ...

Javascript Error:missing =解构声明(Javascript Error: missing = in destructuring declaration)

这不是一个标准的JavaScript错误。 它来自您的编辑器。 您必须为您的Emacs编辑器使用js2模式 (Javascript模式)。 这可能是for循环中缺少的等号。 例: for(i 0; i < arr.length;i++); /* missing = in destructuring declaration */ 但是,如果不查看您的代码,我们只能猜测。 This is not a standard javascript error. It's coming from your e ...

使用`this`的ES6解构赋值(ES6 Destructuring assignment with `this`)

您可以通过给出别名并在圆括号中封装赋值( 等待代码 )来分配给现有对象的属性。 const demo = { nextUrl: 'nextUrl', posts: 'posts' }; const target = {}; // replace target with this ({ nextUrl: target.nextUrl, posts: target.communityPosts } = demo); console.log(target); You can assig ...

在Javascript中解构赋值的好处[关闭](Benefits of destructuring assignments in Javascript [closed])

好处是您不需要重复解构表达式。 当然,在你的例子中它几乎没有什么区别,因为你已经在metadata变量中得到了它。 但如果它是一个非常复杂的表达式,或其他东西,你可以保存一个额外的变量。 例如,比较此功能 function example(metadata) { var englishTitle = metadata.title, localeTitle = metadata.translations[0].title; …; // use englishTitl ...

Javascript重新赋值变量与解构[重复](Javascript re-assign let variable with destructuring [duplicate])

({ latitude, longitude } = props.userLocation.coords); 解构需要在let , const或var声明之后,或者需要在表达式上下文中,以区别于块语句。 ({ latitude, longitude } = props.userLocation.coords); Destructuring needs to be either after a let, const or var declaration or it needs to be in ...

Javascript为初学者分配?(Assignments on Javascript for beginners? [closed])

JavaScript分配 JavaScript作业 JavaScript Assignments JavaScript homeworks

具有解构的对象属性赋值?(Object property assignment with destructuring?)

我想你将不得不重复dst : ({a: dst.a, b: dst.b} = src); I think you’re going to have to repeat dst: ({a: dst.a, b: dst.b} = src);

使用正则表达式后的JavaScript解构赋值(JavaScript destructuring assignment after using regex)

它看起来像你想要的 let marketLabel = 'Set 1 Total Games Over/Under 9.5'; const regexUnderOver = /^Set ([0-9.]+) Total Games (Over)\/(Under) ([0-9.]+)$/; let [fullmatch, firstNum, over, under, lastNum] = regexUnderOver.exec(marketLabel); let browserReturn = ...

对象分配的嵌套解构(Nested Destructuring on Object Assignments)

对于嵌套级别,您可以重复相同的语法,如同对顶级进行解构: 根据您的评论编辑 我需要数组中的对象 let node = { ItemTitle: 'Title', ItemId: 5, Menu: {Item: [{ItemId: 579}]} } let { ItemId: id, // extract `node.ItemId` into a variable called `id` ItemTitle: title, // extract `n ...

相关文章

更多

最新问答

更多
  • 如何保护Solr只允许SELECT请求给用户并禁止其他任何东西?(How to secure Solr to allow SELECT request to only users and disallow anything else?)
  • XPath表达式无效/错误TFHpple SWIFT 1.2(XPath Expression not working/incorrect TFHpple SWIFT 1.2)
  • css3 3D变换不能平滑地制作动画(css3 3D transform doesn't animate smoothly)
  • 运行时错误'91'和Outlook.Application = <对象变量或没有设置块变量>?(Run-time error '91' & Outlook.Application = Object variable or With block variable not set?)
  • 慢的webservice问题(Slow webservice problem)
  • textview的不正确对齐方式(Improper alignment of a textview)
  • 在第一步“Hello World”中出现Java错误(Cannot run “Hello World” program in Eclipse)
  • 为什么十六进制地址是14个字符?(why the hex address is 14 character?)
  • 如何在Python中的不同类中使用变量?(How to use variable in different classes in Python?)
  • asp:GridView HYPERLINKFIELD - datanavigateurlformatstring中的asp代码(asp:GridView HYPERLINKFIELD - asp code inside datanavigateurlformatstring)
  • 关于adaboost算法(About adaboost algorithm)
  • 在Matlab上内置图像(Built in Images on Matlab)
  • java swing:输入键事件时焦点丢失(java swing: Focus lost on enter key event)
  • C#中的通用约束,T是相同的TSomethingElse,对吧?(Generic constraints in C#, T is the same TSomethingElse, right?)
  • 从mybatis中的光标获取数据(Fetching data from cursor in mybatis)
  • 在运行时从XML构建对象的最佳方法(Best way for building objects out of XMLs at runtime)
  • 在整个窗口中拉伸sf :: Sprite(Stretch sf::Sprite across entire window)
  • Selenium Node API Web驱动程序等待超时处理程序(Selenium Node API web driver wait timeout handler)
  • 函数使用并且是map的一部分(循环依赖?)(Function uses and is part of map (circular dependency?))
  • 是否可以在C ++ 14中使用可选模板参数创建类型元组?(Is possible to make a tuple of types with optional template parameters in C++14?)
  • PHP从窗帘后面打印/ f(PHP prints /f from behind the curtains)
  • JFrame的contentPane的LayoutManager(LayoutManager of JFrame's contentPane)
  • 用于Instagram Feed的图像滚动(Image Roll Overs for Instagram Feed)
  • 如何显示拉伸字体(双倍宽度/高度)?(How to display stretched font (double width/height)?)
  • 文件操作API在fileapi.h和stdio.h中的WP8差异?(WP8 differences between file manipulation APIs in fileapi.h and stdio.h?)
  • 保存失败后Rails没有回滚事务()(Rails not rolling back transaction after failed save())
  • jqgrid中的分页问题与数组数据(Pagination problem in jqgrid with array data)
  • 重定向时,通过其他页面上的URL调用javascript函数(Call javascript function through url on otherpage while Redirecting)
  • 如何使用InvokeCommandAction调用我的方法并传入参数?(How do I go about using InvokeCommandAction to call a method of mine and pass in parameters?)
  • Jquerymobile按钮仅显示页面的第一个外观(Jquerymobile buttons are shown only first apperance of the page)