【问题标题】:Prevent arrray.map returning undefined when condition/callback is not met [duplicate]当条件/回调不满足时,防止 ararray.map 返回 undefined [重复]
【发布时间】:2021-12-04 04:59:51
【问题描述】:

我正在编写一些代码,但有些事情让我感到困惑。我有一个名为alarmsList 的数字数组。现在我希望遍历这个列表,如果一个值高于 60,例如,我想创建一个新的对象数组(集合),我们在其中存储高值,它是原始数组的索引。所以取下面的代码

const alarmsList = [1, 61, 77, 4, 5, 6, 7, 8, 85, 4, 3, 55];

const highAlarmsList = alarmsList.map((item, index) => {
    if(item > 60) {
        return ({ value: item, index })
    }
});

console.log(highAlarmsList)

console.log 输出以下内容

[
    undefined,
    {
        "value": 61,
        "index": 1
    },
    {
        "value": 77,
        "index": 2
    },
    undefined,
    undefined,
    undefined,
    undefined,
    undefined,
    {
        "value": 85,
        "index": 8
    },
    undefined,
    undefined,
    undefined
]

这个输出是我需要的,但我如何防止返回未定义的值?我考虑过使用 array.filter 但这似乎不合适?我应该使用不同的数组方法吗?我不想使用 for 循环并推送到新数组,除非这是在不返回未定义值的情况下实现新数组的最佳/唯一方法。

【问题讨论】:

  • 是的,.filter() 在这里是合适的,但这将涉及对您的数组/过滤数组的额外传递。还有.reduce(),您可以使用它同时进行过滤和映射,或者.flatMap(),但这些通常不像for循环或过滤器+映射那样可读(参见:Map and filter an array at the same time)

标签: javascript arrays


【解决方案1】:

您可以使用Array.filter() 来删除undefined 值,方法是使用Boolean 作为谓词:

const alarmsList = [1, 61, 77, 4, 5, 6, 7, 8, 85, 4, 3, 55];

const highAlarmsList = alarmsList.map((item, index) => {
  if(item > 60) {
    return ({ value: item, index })
  }
}).filter(Boolean);

console.log(highAlarmsList)

您可以使用 Array.flatMap() 并返回空数组而不是 undefined,但这可能会影响大型数组的性能:

const alarmsList = [1, 61, 77, 4, 5, 6, 7, 8, 85, 4, 3, 55];

const highAlarmsList = alarmsList.flatMap((item, index) => 
  item > 60 ? { value: item, index } : []
);

console.log(highAlarmsList)

【讨论】:

    【解决方案2】:

    map 通过对数组的每个元素运行回调来创建一个新数组。如果条件不满足,它将返回 undefined 或 null。所以不可能从输出中跳过元素。

    您也可以选择减少或过滤

    const alarmsList = [1, 61, 77, 4, 5, 6, 7, 8, 85, 4, 3, 55];
    
    const highAlarmsList = alarmsList.reduce((acc, item, index) => {
      item > 60 && acc.push({
        value: item,
        index
      })
      return acc;
    }, [])
    
    console.log(highAlarmsList)

    【讨论】:

      猜你喜欢
      • 2021-05-03
      • 2018-04-13
      • 1970-01-01
      • 2023-02-09
      • 2013-08-10
      • 1970-01-01
      • 1970-01-01
      • 2022-12-10
      • 1970-01-01
      相关资源
      最近更新 更多