有条件的传播元素 [英] Conditional spread element
本文介绍了有条件的传播元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
const cond = false
const extraInfo = [
{
a: 11,
b: 25
},
{
a: 12,
b: 34
},
{
a: 1,
c: 99
}
]
const userInfo = [
{
z: 8
},
{
z: 10
},
...(cond && extraInfo)
]
何时 cond
是真的,我想要额外的和用户信息。
When cond
is true, I want both extra and user info.
当 cond
为false,只需要userInfo。
When cond
is false, only userInfo is needed.
问题是当 cond
为false时,我获取
The issue is when cond
is false, I get
TypeError :(中间值)(中间值)(中间值)[Symbol.iterator]不是函数
TypeError: (intermediate value)(intermediate value)(intermediate value)[Symbol.iterator] is not a function
我的理解是我不允许使用布尔值作为展开元素,在这种情况下 ... false
。
My understanding is that I am not allowed to use a boolean as a spread element, in this case ...false
.
但 ...(cond?extraInfo:{})
不似乎也有用。
发生了什么事?
推荐答案
只需付出代价
...(cond ? extraInfo : [])
真实演示
var cond = true;
var extraInfo = [
{
a: 11,
b: 25
},
{
a: 12,
b: 34
},
{
a: 1,
c: 99
}
];
var userInfo = [
{
z: 8
},
{
z: 10
},
...(cond ? extraInfo : [])
];
console.log( userInfo );
假的演示
var cond = false;
var extraInfo = [
{
a: 11,
b: 25
},
{
a: 12,
b: 34
},
{
a: 1,
c: 99
}
];
var userInfo = [
{
z: 8
},
{
z: 10
},
...(cond ? extraInfo : [])
];
console.log( userInfo );
这篇关于有条件的传播元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文