JS 找数组中的最大值的方法统计
在开发中,我们经常需要找到数组中元素最大的,下面我列举了几种方法;
一、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
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
