如果以前的较低
我有一系列减少的数字,但我希望它永远不会减少:
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以在列表中的当前和前面条目之间使用
Math.max
:请注意,您可以/应该只使用
Math.max(... A.Slice(0,i+1))
,因为v
isa [i]
,我以清楚代码正在做什么的方式写了它。You could use
Math.max
between the current and the preceding entries in the list:Note that you could/should just use
Math.max(...a.slice(0, i+1))
sincev
isa[i]
, I wrote it the way I did for clarity as to what the code is doing.