ES6语法参考:使用扩展和布尔短路在声明期间有条件地向对象添加字段 [英] ES6 syntax reference: use spread and boolean short circuiting to conditionally add fields to an object during declaration

查看:189
本文介绍了ES6语法参考:使用扩展和布尔短路在声明期间有条件地向对象添加字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想构造一个这样的对象:

I want to construct an object like this:

const obj = {
    a: 'a',  // only add this if "someCondition" is true
    b: 'b',  // only add this if "someCondition" is false
    always: 'present', // add this in any case
}

这有效:

const obj = { always: 'present' }
if (someCondition) { obj.a = 'a' }
if (!someCondition) { obj.b = 'b' }

但是,我正在寻找一种使用ES6语法的更简洁的方法.

However, I'm looking for a more concise way using ES6 syntax.

推荐答案

可以使用ES6语法在对象声明期间有条件地添加字段.

It is possible using ES6 syntax to conditionally add fields during declaration of an object.

如果对象的使用者不能容忍具有null/undefined/任何值的字段,并且您不想编写多个语句来正确声明该对象,这将很有用:

This is useful if the consumer of the object will not tolerate fields with null / undefined / whatever values, and you do not want to have to write multiple statements to correctly declare the object:

const obj = {
  ...(someCondition && {a: 'a'}),
  ...(!someCondition && {b: 'b'}),
  always: 'present'
}

那如何运作?让我们看一下...(true && {a: 'a'}). ES6 扩展运算符"..." 将迭代{"a":"a"}中的每个field-> value对,并将它们应用于x.

So how does that work ? Lets look at ...(true && {a: 'a'}). The ES6 spread operator "..." will iterate each of the field->value pairs in { "a": "a" } applying them to x.

true && x表达式将返回x,而false && x表达式将返回false.这称为短路评估

The true && x expression will return x, whereas false && x will return false. This is known as short circuit evaluation

因此,如果逻辑表达式为true,则散布运算符将添加字段,如果逻辑表达式为true,则将不添加任何内容.

So if the logical expression is true then the spread operator will add the fields, and if it is not true it will not add anything.

这篇关于ES6语法参考:使用扩展和布尔短路在声明期间有条件地向对象添加字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆