js遍历查找数组中最大值与最小值的方法

第一种 使用for循环

<script> 
// 查找数组中最小值
function mathMin(arr){
  var min = arr[0];
  for(var i = 1; i < arr.length; i++) {
    if(arr[i] < min) {
      min = arrs[i];
    }
  }
  return min;
}
// 代码测试
var test = [2,4,5,6,7,0,9,10,15,1];
console.log(mathMin(test));//0
 
// 在数组中查找最大值
function mathMax(arr) {
  var max = arr[0];
  for(var i = 1; i < arr.length; i++) {
    if(arr[i] > max) {
      max = arrs[i];
    }
  }
  return max;
}
// 代码测试
var test = [1,4,5,6,7,9,10,15,55];
console.log(mathMax(test));//55
</script>

第二种 通过数组的sort排序方法先把数据排序,再找出最大值和最小值

正常数组:

var test = [2,4,5,6,7,0,9,10,15,1];
test.sort((a, b) => a - b) // 从小到大排序
console.log('最小值', test[0])
console.log('最大值', test[test.length -1])

数组对象:

var test = [{id: 123, price: 70}, {id: 124, price: 60}, {id: 125, price: 90}];
test.sort((a, b) => a.price - b.price)
console.log('最小价格元素', test[0])
console.log('最大价格元素', test[test.length -1])

第三种 使用Math

//  接受的值:整数,浮点数,数字字符串。  无效值:非数字字符串,空变量,空数组都将返回NaN(非数字)。
const arr = [1, 2, 3];
Math.max(…arr); // 3
Math.min(…arr); // 1

示例:有效值

console.log(Math.max(-1, 4, 6, 12));
console.log(Math.max(3.14, 43, 1, 0.2));
console.log(Math.max(0, -13, 4, 654));
console.log(Math.max("0.65", "-23"));

输出:
12
43
654
-0.65



  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值