简体   繁体   English

使用条件元素定义JavaScript数组文字

[英]Define JavaScript array literal with conditional elements

I want to create a JavaScript array using a literal containing the elements. 我想使用包含元素的文字来创建JavaScript数组。 I only want a chunk of those elements (somewhere in the middle of the array) to be included if a certain expression is true. 如果某个表达式为真,我只希望包含这些元素的一部分(在数组中间的某个位置)。 I can obviously create the array with the always-present elements only then programmatically insert the additional elements at the appropriate index if the condition is true, but I don't want to do that because the non-ES6 ways of doing it are not very pretty and you have to mentally think about indexes to understand where the conditional elements are going to go if the condition is true (not very readable). 我显然可以使用始终存在的元素创建数组,然后在条件为真的情况下以编程方式在适当的索引处插入其他元素,但是我不想这样做,因为非ES6的处理方式不是很如果条件为真(不是很易读),那么您就必须认真思考索引,以了解条件元素将要去往何处。 Here is a simplified example of what I know how to do (but dislike) versus what I'd like to do (but don't know how). 这是我知道该怎么做(但不喜欢)与我想做什么(但不知道怎么做)的简化示例。 In the last example, instead of undefined at the index, I simply don't want an element there. 在最后一个示例中,我只是不想在该元素上而不是在索引中undefined Is there a way to achieve this with a literal and expressions, or will I have to end up doing some array manipulation to achieve this? 有没有一种方法可以通过文字和表达式来实现,或者我将不得不做一些数组操作来实现这一点?

 function createArrayTheWayIDislike(condition) { var array = [ 'a', 'd' ]; if(condition) { array.splice.apply(array, [1, 0].concat(['b', 'c'])); } console.log(array); } function createArrayTheWayIWantTo(condition) { var array = [ 'a', condition ? 'b' : undefined, condition ? 'c' : undefined, 'd' ]; console.log(array); } createArrayTheWayIDislike(true); createArrayTheWayIDislike(false); createArrayTheWayIWantTo(true); createArrayTheWayIWantTo(false); 

You can filter the results before returning the array 您可以在返回数组之前过滤结果

 function createArrayTheWayIWantTo(condition) { var array = [ 'a', condition ? 'b' : undefined, condition ? 'c' : undefined, 'd' ].filter(e => e); console.log(array); } createArrayTheWayIWantTo(true); createArrayTheWayIWantTo(false); 

How about using array destructuring, with a ternary operator to do this? 如何使用带有三元运算符的数组解构来做到这一点? Here's an example: 这是一个例子:

 // Replace with your real conditions const condition1 = true; const condition2 = false; const array = [ 'a', ...condition1 ? ['b'] : [], ...condition2 ? ['c'] : [], 'd' ]; // Should log ['a', 'b', 'd']; console.log(array); 

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

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