在开发中,我们经常需要找到数组中元素最大的,下面我列举了几种方法;

一、for循环

1.基本用法(冒泡排序)

  let arr = [12, 223, 44, 56, 785, 34, 888];
  let max = arr[0];
  for (let i = 1; i < arr.length; i++) {
      if (arr[i] > max) {
          max = arr[i]
      }
  }
  console.log(max);// 888

2.三元运算符(优化if判断)

 let arr = [12, 223, 44, 56, 785, 34, 888];
 let max = arr[0];
 for (let i = 1; i < arr.length; i++) {
     max = max > arr[i] ? max : arr[i]
 }
    console.log(max);//888

二、利用数组的sort()方法进行排序

1.基本用法

  let arr = [12, 223, 44, 56, 785, 34, 888];
  let newArr = arr.sort(function (a, b) {
      return b - a
  });
  console.log(newArr[0]);//888

2.箭头函数(优化匿名函数)

 let arr = [12, 223, 44, 56, 785, 34, 888];
 let newArr = arr.sort((a, b) => b - a);
 console.log(newArr[0]);// 888

三、利用数组的reduce()或者reduceRight()方法

reduce()和reduceRight()方法使用指定的函数将数组元素进行组合,生成单个值。
这在函数式编程中可称为“注入”和“折叠”。

let arr = [12, 223, 44, 56, 785, 34, 888];
let max = arr.reduce((a, b) => a > b ? a : b );
console.log(max);//888

四、利用Math对象的max()方法和函数的apply()方法

Math.max通过apply()去接收一个数组arr作为参数,arr数组的元素传入Math.max()中

let arr = [12, 223, 44, 56, 785, 34, 888];
let max = Math.max.apply(null, arr);
console.log(max);//888

五、利用ES6的扩展运算符

扩展运算符(spread)是三个点(…),它将一个数组转为用逗号分隔的参数序列。

let arr = [12, 223, 44, 56, 785, 34, 888];
let max = Math.max(...arr);
console.log(max);// 888
Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐