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

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

问题描述

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

how can i define conditional array elements? i want to do something like this:

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

这按预期工作:["foo", "bar"]

但是,如果将cond设置为false,则会得到以下结果:["foo", false]

But if I set cond to false, I get the following result: ["foo", false]

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

How could I define an array with a conditional element?

推荐答案

您可以在条件为false时将数组扩展到数组内部,以保持项目数组的整洁.

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

这是您的操作方式:

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

console.log(items)

说明:

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

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

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

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.

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

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天全站免登陆