简体   繁体   English

如何有条件地填充数组?

[英]How to fill an Array conditionally?

I have the following JS code:我有以下JS代码:

let a = false
let b = true
let c = [...(a ? {d: 1} : {})]

I'm trying to set c to [{d: 1}] if a is true, and set it to [] if a is false.如果 a 为真,我试图将c设置为[{d: 1}] ,如果a为假,则将a设置为[] It's throwing the error object is not iterable (cannot read property Symbol(Symbol.iterator))它抛出错误object is not iterable (cannot read property Symbol(Symbol.iterator))

Why is it throwing this error and how can I fix it?为什么会抛出此错误,我该如何解决?

You need to wrap the expressions in arrays.您需要将表达式包装在数组中。

 const a = false, b = true, c = [...(a ? [{ d: 1 }] : [])], d = [...(b ? [{ d: 1 }] : [])]; console.log(c); console.log(d);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM