利用展开操作符简化对象上属性添加的操作

对象

经常情况下,需要根据条件动态向对象上添加属性,比如请求的参数。

const params = {prop1:'1'}

if(query){
    params['prop2']= 2
}

通过展开操作符 spread(...)可避免使用 if 从而简化操作。

考察如下的代码:

const prop1 = 1,
  prop2 = "2";
const condition = false;
console.log({ a: prop1, b: prop2, ...(condition ? { prop3: "3" } : {}) });
// 结果 { a: 1, b: '2' }

其中空对象 {} 处可使用 nullundefined 代替能够达到同样的效果。

借助逻辑运算符的短路特性可进一步简化:

const prop1 = 1,
  prop2 = "2";
const condition = false;
console.log({ a: prop1, b: prop2, ...condition && { prop3: "3" }});
// 结果: { a: 1, b: '2' }

只有 conditiontrue 时才会将后面的对象展示,否则表达式返回 false,而 false 展示是没效果的。

特别地,被展开的字段就是所需要的名字时,进一步简化成:

const prop1 = 1,
  prop2 = "2",
  prop3=3;
const condition = true;
console.log({ prop1,prop2, ...condition && {prop3}});
// 结果: {prop1: 1, prop2: "2", prop3: 3}

数组

对于数组类似,只不过展示时需要用中括号包裹

const items = [
  'foo',
  ... true ? ['bar'] : [],
  ... false ? ['falsy'] : [],
]
// 结果 ["foo", "bar"]

The text was updated successfully, but these errors were encountered:

CC BY-NC-SA 署名-非商业性使用-相同方式共享
原文地址:https://www.cnblogs.com/Wayou/p/14761263.html