如果以前的较低

发布于 2025-02-07 03:45:24 字数 1034 浏览 0 评论 0原文

我有一系列减少的数字,但我希望它永远不会减少:

const数字= [0,1,1,2,3,4,5,1,2];

所需结果是:

<代码> [0、1、2、3、4、5、5、5]

我知道如何实现循环:

for (let index = 0; index < numbers.length; index++) {
    const element = numbers[index];
    if (index > 0) {
      const prevEl = numbers[index - 1];
      if (element < prevEl) {
        numbers[index] = prevEl;
      }
    }
  }

但是使用地图时

numbers.map((item, index) => {
    const prevEl = numbers[index - 1];
    if (item < prevEl) {
        return prevEl;
      }
    return item;
})

const numbers = [0,1,2,3,4,5,1, 2];

const result = numbers.map((item, index) => {
    const prevEl = numbers[index - 1];
    if (item < prevEl) {
        return prevEl;
      }
    return item;
});

console.log(result); // [0, 1, 2, 3, 4, 5, 5, 2]

我得到的是:[0、1、2、3、4、5、5、2]

实现这一目标的功能方法是什么?

I have array of numbers that decreases, but I want it never to decrease:

const numbers =[0,1,2,3,4,5,1, 2];

Desired result is:

[0, 1, 2, 3, 4, 5, 5, 5]

I know how to achieve it with for loop:

for (let index = 0; index < numbers.length; index++) {
    const element = numbers[index];
    if (index > 0) {
      const prevEl = numbers[index - 1];
      if (element < prevEl) {
        numbers[index] = prevEl;
      }
    }
  }

But when using map

numbers.map((item, index) => {
    const prevEl = numbers[index - 1];
    if (item < prevEl) {
        return prevEl;
      }
    return item;
})

const numbers = [0,1,2,3,4,5,1, 2];

const result = numbers.map((item, index) => {
    const prevEl = numbers[index - 1];
    if (item < prevEl) {
        return prevEl;
      }
    return item;
});

console.log(result); // [0, 1, 2, 3, 4, 5, 5, 2]

I get this instead: [0, 1, 2, 3, 4, 5, 5, 2]

What would be the functional way to achieve this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

柠檬 2025-02-14 03:45:24

您可以在列表中的当前和前面条目之间使用Math.max

const numbers = [0,1,2,3,4,5,1, 2];

result = numbers.map((v, i, a) => Math.max(v, ...a.slice(0, i)))
console.log(result)

请注意,您可以/应该只使用Math.max(... A.Slice(0,i+1)),因为v is a [i],我以清楚代码正在做什么的方式写了它。

You could use Math.max between the current and the preceding entries in the list:

const numbers = [0,1,2,3,4,5,1, 2];

result = numbers.map((v, i, a) => Math.max(v, ...a.slice(0, i)))
console.log(result)

Note that you could/should just use Math.max(...a.slice(0, i+1)) since v is a[i], I wrote it the way I did for clarity as to what the code is doing.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文