简体   繁体   English

通过 if 条件从 `Array.flatMap()` 中不返回任何元素

[英]Return no element from `Array.flatMap()` by if condition

I have this code:我有这个代码:


  const myFunc = function (t) {
    return myArray.flatMap(clip =>
      (t < clip.start || t < clip.end) ? // Valid objects are returned in this *if* condition
        [
          { time: clip.start },
          { time: clip.end }
        ] : // how to return nothing in this *else* condition. Absolutely nothing?
        [
          {  },
          {  }
        ]
    )
  }

The above code used a ternary operator of condition? exprIfTrue: exprIfFalse上面的代码使用了条件的三元运算符condition? exprIfTrue: exprIfFalse condition? exprIfTrue: exprIfFalse . condition? exprIfTrue: exprIfFalse

Currently I'm returning empty objects of { } in the case of exprIfFalse .目前我在exprIfFalse的情况下返回{ }的空对象。

How can I return nothing in the case of exprIfFalse ?exprIfFalse的情况下,我怎样才能不返回任何内容? I mean, I want absolutely nothing.我的意思是,我什么都不想要。 I mean no array element.我的意思是没有数组元素。

Why cant you just return an empty array, any how Array.flat will remove those empty array from final code.为什么不能只返回一个空数组, Array.flat将如何从最终代码中删除这些空数组。 In your case the array is not empty as [] , its an array with two empyty objects as [{}, {}] that will produce two empty objects {}, {} in the final output after Array.flat在您的情况下,数组不是空的[] ,它是一个具有两个空对象的数组[{}, {}]将在 Array.flat 之后的最终Array.flat中产生两个空对象{}, {}

You have to return something from flatMap .你必须从flatMap返回一些东西。 If you return nothing, the corresponding nodes will be added as undefined .如果什么都不返回,则相应的节点将被添加为undefined That wont be removed with Array.flat .这不会被Array.flat删除。 Best option is to return an empty array as below.最好的选择是返回一个空数组,如下所示。

Pseudo Code伪代码

 const myArray = [1, 2, 3, 4, 5]; const myFunc = function (t) { return myArray.flatMap(clip => (clip % 2 === 0)? // Valid objects are returned in this *if* condition [ { value: clip }, { value: clip } ]: // how to return nothing in this *else* condition. Absolutely nothing? [] ) } console.log(myFunc());

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

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