如何定义带有条件元素的数组? [英] How to define an array with conditional elements?

查看:23
本文介绍了如何定义带有条件元素的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何定义条件数组元素?我想做这样的事情:

const cond = true;const myArr = [foo", cond &&酒吧"];

这按预期工作并导致 ["foo", "bar"] 但如果我将 cond 设置为 false,我得到以下结果:["foo", false]

如何定义带有条件元素的数组?

解决方案

当条件为 false 时,您可以将数组散布在数组内部,以保持 items 数组的清洁.>

您可以这样做:

//会导致 ['foo', 'bar']常量项 = ['富',... 真的 ?['酒吧'] : [],... 错误的 ?['假'] : [],]console.log(items)

说明:

正如你所见,三元运算符总是返回一个数组.

如果条件为true,则返回['bar'],否则返回空数组[].

之后我们展开 ... 结果数组(来自三元运算)并将数组的项推送到父数组.

如果没有任何数组项(当三元检查为false时),那么什么都不会被推送,这是我们的目标.

<小时>

在其他答案中,我解释了相同的想法,但针对对象.您也可以在此处查看.

How can I define conditional array elements? I want to do something like this:

const cond = true;
const myArr = ["foo", cond && "bar"];

This works as expected and results in ["foo", "bar"] but if I set cond to false, I get the following result: ["foo", false]

How can I define an array with a conditional element?

解决方案

You can spread an array inside of an array, in order to keep items array clean, when the condition is false.

Here's how you can do it:

// Will result in ['foo', 'bar']
const items = [
  'foo',
  ... true ? ['bar'] : [],
  ... false ? ['falsy'] : [],
]

console.log(items)

Explanations:

As you can see the ternary operator always returns an array.

If the condition is true, then it returns ['bar'], otherwise an empty array [].

After that we spread out ... the resulted array (from the ternary operation) and the array's items are pushed to the parent array.

If there aren't any array items (when the ternary check is false), then nothing will be pushed, which is our goal.


In other answer I explained the same idea, but for objects. You can check it too here.

这篇关于如何定义带有条件元素的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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