gpt4 book ai didi

javascript - 查找数组中的最大值(array.find)

转载 作者:行者123 更新时间:2023-12-02 20:50:46 25 4
gpt4 key购买 nike

我正在学习 Javascipt,实际上我正在学习数组方法。我的想象练习依赖于通过 array.find 方法找到数组中的最大/最小值。

实际上我就是这样做的,但是脚本返回给我“未定义”。请帮忙。 :)

const scores = [10, 20, 30, 22, 25, 109, 90];

const maxScore = scores.find(score => {
let max = 0;
for (let i=1; i < scores.length; i++){
if(score[i] > max){
max = score[i];
};
};
return max;
});
console.log(maxScore);

P.S.我知道“Math.max.apply”,但我必须通过 array.find 和简单循环来完成。

最佳答案

您可以对索引进行闭包,以便从末尾开始循环,并使用一个临时最大值,该最大值在开始时未定义,并从第一个元素获取第一个值。

然后在临时索引处的值小于score时循环,将该值存储在max中,重复。

如果索引加一等于临时索引,最后返回结果。

这种方法需要一个循环。 find 从数组开头迭代,从数组末尾开始内循环,如果两个索引交叉,则找到结果。

const
scores = [100, 20, 30, 22, 25, 109, 90],
maxScore = scores.find(
((j, max) => (score, i, array) => {
if (max === undefined) {
max = score;
j = array.length;
}
if (score < max) return;
while (array[j - 1] < score) max = array[--j];
return i + 1 === j;
})
()
);

console.log(maxScore);

关于javascript - 查找数组中的最大值(array.find),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61612527/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com