javascript 使用forEach()循环数组以获得最大数

bxpogfeg  于 2023-05-16  发布在  Java
关注(0)|答案(6)|浏览(173)

我尝试使用forEach JavaScript方法提取数组的最大数字。这是我目前所知道的,但我知道这是不正确的。

var arr = [2,3,4];
var largest = 0;
 
arr.forEach(function(elem){
  if(largest < elem) 
  largest = elem;
  console.log(largest);
});
mm9b1k5b

mm9b1k5b1#

这会有用的

var arr = [2,3,4];
var largest = 0;

arr.forEach(function(elem){
  if(largest < elem) 
  largest = elem;
});

console.log(largest);

但你为什么要这么做为什么不使用Max?

var largest = Math.max.apply(Math, arr);
iih3973s

iih3973s2#

为了覆盖数组中的负数,将largest指定为数组中的第一个元素是安全的。

var arr = [2,3,4];
var largest = arr[0];
 
arr.forEach(function(elem){
  if(largest < elem) 
  largest = elem;
});
console.log(largest);
eni9jsuy

eni9jsuy3#

你可以简单地使用spread operator:

var arr = [2,3,4];
var largest = Math.max(...arr); 
console.log(largest);
t9aqgxwy

t9aqgxwy4#

如果将console.log(largest);放在forEach循环之外,它将打印数组中最大的数字。

fdbelqdn

fdbelqdn5#

var
    a = [2,3,4,2,1,9],
    largest = 0;

a.forEach(function(value){
    console.log('current array element value: ' + value + '.  Is it larger than the largest?', (largest > value));
    if (largest < value) largest = value;
    console.log('largest value now is: ', largest);
});
console.log('largest is changed here, because it was not redefined inside the function of the forEach method: ', largest, '.\n But it was defined within its context.');
xzv2uavs

xzv2uavs6#

function greatest(array) {
    if(array == undefined){
        console.log('There are no elements in array.');
    }

    const max = array.reduce(function(first, next){
        return first > next ? first : next; 
    });

    console.log(`Maximum element is ${max}`);
}

相关问题