Sunny-117 / js-challenges

✨✨✨ Challenge your JavaScript programming limits step by step

Home Page:https://juejin.cn/column/7244788137410560055

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

数组中的最大值

Sunny-117 opened this issue · comments

数组中的最大值
// 三种方法
let arr = [5,2,7,9]
// let res = Math.max(...arr)
// let res = arr.sort()[arr.length-1]
let res=arr[0]
for(let i=0;i<arr.length;i++){
  if(arr[i]>res){
    res = arr[i]
  }
}
console.log(res);
// 三种方法
let arr = [5,2,7,9]
// let res = Math.max(...arr)
// let res = arr.sort()[arr.length-1]
let res=arr[0]
for(let i=0;i<arr.length;i++){
  if(arr[i]>res){
    res = arr[i]
  }
}
console.log(res);

arr.sort()[arr.length - 1] 这种方法不能得到答案,sort函数需要指定排序函数才行。因为默认的排序函数是会将数组中的数据转化成字符串进行比较的,而字符串大小比较是根据字典序的(如:会出现 "11" < "2" 的情况)
正确写法应该是:
arr.sort(function(a, b) { return a -b })[arr.length-1]

// 三种方法
let arr = [5,2,7,9]
// let res = Math.max(...arr)
// let res = arr.sort()[arr.length-1]
let res=arr[0]
for(let i=0;i<arr.length;i++){
  if(arr[i]>res){
    res = arr[i]
  }
}
console.log(res);

arr.sort()[arr.length - 1] 这种方法不能得到答案,sort函数需要指定排序函数才行。因为默认的排序函数是会将数组中的数据转化成字符串进行比较的,而字符串大小比较是根据字典序的(如:会出现 "11" < "2" 的情况) 正确写法应该是: arr.sort(function(a, b) { return a -b })[arr.length-1]

感谢指正

commented
const arr = [1, 3, 55, 77, 1000];
// 1. 调用Math
let res = Math.max(...arr);
// 2. 排序
arr.sort((a, b) => a - b)[arr.length - 1];
// 3. 可以采用快排
// 4. 直接获取最大值
function getMax(arr){
    let res = -Infinity;
    for(let i = 0; i < arr.length; i++){
        res = Math.max(res, arr[i]);
    }
    return res;
}
commented
function getMaxInArr(arr) {
  return arr.reduce((acc, cur) => acc > cur ? acc : cur)
}
const arr = [5,2,7,9]

// 1. 排序取值
const max1 = arr.sort()[arr.length - 1]

// 2. 使用 Math.max
const max2 = Math.max(...arr)

// 3. 循环取值
const max3 = arr.reduce((t, e) => (t > e ? t : e), 0)
const arr = [5,2,7,9]

// 1. 排序取值
const max1 = arr.sort()[arr.length - 1]

// 2. 使用 Math.max
const max2 = Math.max(...arr)

// 3. 循环取值
const max3 = arr.reduce((t, e) => (t > e ? t : e), 0)

第三个方法应该是

const max3 = arr.reduce((t, e) => (t > e ? t : e), Number.MIN_SAFE_INTEGER);

或者是

const max3 = arr.reduce((t, e) => (t > e ? t : e));