在数组中找到最大值(array.find)

问题描述 投票:0回答:1

我正在学习Javascipt,实际上是通过数组方法即时播放情节。我的虚构练习依赖于通过array.find方法在array中找到Max / Min值。

最初,我确实做了类似的事情,但是脚本返回了我“ Undefined”。请帮忙。 :)

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和简单循环来完成。

javascript arrays max min
1个回答
0
投票

find适用于每个数组元素。因此,将max置于find方法和log max之外。另外有两个错别字

const scores = [10, 20, 30, 22, 25, 109, 90];
let max = 0;
const maxScore = scores.find((score) => {

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

0
投票

尝试一下:

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

let max = 0;
scores.find(score => { if(score > max) max = score });
console.log(max);

您当前的代码正在循环循环scores数组,而JavaScripts .find实际上已经循环了该数组。

© www.soinside.com 2019 - 2024. All rights reserved.