对象经常情况下,需要根据条件动态向对象上添加属性,比如请求的参数。 const params = {prop1:'1'} if(query){ params['prop2']= 2 } 通过展开操作符 spread( 考察如下的代码: const prop1 = 1, prop2 = "2"; const condition = false; console.log({ a: prop1, b: prop2, ...(condition ? { prop3: "3" } : {}) }); 其中空对象 借助逻辑运算符的短路特性可进一步简化: const prop1 = 1, prop2 = "2"; const condition = false; console.log({ a: prop1, b: prop2, ...condition && { prop3: "3" }}); 只有 特别地,被展开的字段就是所需要的名字时,进一步简化成: const prop1 = 1, prop2 = "2", prop3=3; const condition = true; console.log({ prop1,prop2, ...condition && {prop3}}); 数组对于数据有类似,只不过展示时需要用中括号包裹 const items = [ 'foo', ... true ? ['bar'] : [], ... false ? ['falsy'] : [], ] |
The text was updated successfully, but these errors were encountered: |
相关文章
- 02-19利用展开操作符简化对象上属性添加的操作