Sometimes we need to find the maximum value, the minimum value, in an array.
First say the maximum value:
Find the maximum value inside the array
Let arr=[2,5,8,9,3,50,1];
function Maxnum () {
Let Max=arr[0]; If the first item is the maximum value
For a let i=1;i<arr.length;i++ {//compares the other items in the data in turn with the first item.
if (Arr[i]>max) {//If an item in the array is found to be larger than the largest item we set previously, replace it in the order
Max=arr[i];
}
}
return Max;
}
Console.log (Maxnum ())
The same minimum value:
function Minnum () {
Let Min=arr[0]; If the first item is the minimum value
For a let i=0;i<arr.length;i++ {//compares the other items in the data in turn with the first item.
if (arr[i]<min) {//If an item in the array is found to be less than the largest item we set previously, replace it in the order
Min=arr[i];
}
}
return min;
}
Console.log (Minnum ());
The results were:
Find the maximum value in the array, the minimum value