使用forEach()循环数组的最大数字

时间:2016-02-15 19:44:19

标签: javascript arrays loops foreach

我试图使用forEach Javascript方法拉出最大数量的数组。这是我到目前为止所做的,但我知道这不正确。



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

6 个答案:

答案 0 :(得分:6)

这将有效

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

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

console.log(largest);

但你为什么要这样做呢?为什么不使用Math max?

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

答案 1 :(得分:1)

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

答案 2 :(得分:1)

要覆盖数组中的负数,可以安全地将largest指定为数组中的第一个元素。

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

答案 3 :(得分:1)

您可以简单地使用传播运算符:

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

答案 4 :(得分:0)

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.');

答案 5 :(得分:0)

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}`);
}