【问题标题】:Is it possible to filter and modify the contents of a Javascript array in one go?是否可以一次性过滤和修改 Javascript 数组的内容?
【发布时间】:2021-05-28 10:25:44
【问题描述】:

正如标题所述,我想知道是否可以过滤和排列然后一次性修改值?不过,最好用一个例子来解释。

假设我有一个数字数组,我想过滤该数组以仅包含正数,然后对剩余的数字进行某种计算,例如乘以 10。我是否必须过滤数组然后执行迭代来修改值还是我可以做这样的事情?

const ages = [-243, -132, 112, 40, -96];
const filtered = ages.filter((number => (number > 0)) * 10);

【问题讨论】:

  • "在剩余的数字上" - 在过滤器中进行修改将对所有数字进行。过滤器还需要一个布尔返回值,因此即使您进行了修改,我也不确定它是否会影响数组。

标签: javascript arrays filter


【解决方案1】:

您可以使用单个 reduce 函数来完成此操作

const ages = [-243, -132, 112, 40, -96];

const result = ages.reduce((arr, num) => {
  if (num > 0) arr.push(num * 10);
  return arr;
}, []);

console.log(result);

或使用flatMap的单行函数

const ages = [-243, -132, 112, 40, -96];

const result = ages.flatMap((num) => (num > 0 ? [num * 10] : []));

console.log(result);

【讨论】:

    【解决方案2】:

    我不这么认为..我会这样做:

    const ages = [-243, -132, 112, 40, -96];
    const filtered = ages.filter(number => number > 0).map(x => x * 10);
    
    console.log(filtered);

    【讨论】:

    • 这基本上是我要找的,我会在计时器到期时将您的答案标记为已接受。
    • 您可以使用过滤器命令过滤和修改而不使用map:请参阅this section in the docs。优点是不会在数组中循环两次。显然,这么小的数组几乎没有什么区别,所以接受的答案更清晰。
    • 您不需要过滤然后映射,而是使用reduce并在单个函数中完成所有工作
    【解决方案3】:

    简短的回答是可以

    1. 您可以一次性过滤和修改数组。

      console.log(
      [243 * 10, -132, 112, 40, -96]
      .filter((age, index, arr) => { 
             arr[index+1] *= 10;
             return age > 0;
     }))
    1. 但我认为我们应该尽可能避免它。因为它会改变原始数组。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-29
      • 2022-01-07
      • 2014-02-28
      • 1970-01-01
      • 2019-03-16
      • 1970-01-01
      • 1970-01-01
      • 2011-03-04
      相关资源
      最近更新 更多