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.');
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}`);
}
6条答案
按热度按时间mm9b1k5b1#
这会有用的
但你为什么要这么做为什么不使用Max?
iih3973s2#
为了覆盖数组中的负数,将
largest
指定为数组中的第一个元素是安全的。eni9jsuy3#
你可以简单地使用spread operator:
t9aqgxwy4#
如果将
console.log(largest);
放在forEach循环之外,它将打印数组中最大的数字。fdbelqdn5#
xzv2uavs6#