使用 javascript 查找最小值和最大值

时间:2021-06-11 20:13:12

标签: javascript

接收一个整数数组作为参数 •

  • 函数遍历数组以确定最小值和 数组中的最大值

  • 显示计算的信息,如下图所示:

函数名([-8, -1, -87, -14, -81, -74, -20, -86, -61, -10]);

// 将在控制台中产生以下消息:

The minimum value in the array is: -87, the maximum value is -1

2 个答案:

答案 0 :(得分:1)

Math.minMath.max 返回最小值和最大值。由于您希望函数将其打印到控制台,因此请使用 console.log 打印出这些值,以及一个模板化的字符串以使其具有您想要的格式。

const minAndMax = (arr) => console.log(`The minimum value in the array is: ${Math.min(...arr)}, the maximum value is ${Math.max(...arr)}`)

minAndMax([-8, -1, -87, -14, -81, -74, -20, -86, -61, -10]);

答案 1 :(得分:0)

这会起作用。

function yourFunc(arr){
 arr = arr.sort( (a,b) => a -b );
 console.info(`The minimum value in the array is: ${arr[0]}, the maximum value is ${arr[arr.length - 1]}`);
}
yourFunc([-8, -1, -87, -14, -81, -74, -20, -86, -61, -10])