js-challenges icon indicating copy to clipboard operation
js-challenges copied to clipboard

数组中的最大值

Open Sunny-117 opened this issue 3 years ago • 8 comments

Sunny-117 avatar Nov 03 '22 08:11 Sunny-117

// 三种方法
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);

CXGBro avatar Dec 24 '22 03:12 CXGBro

// 三种方法
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]

BingGuanqi avatar Jan 12 '23 01:01 BingGuanqi

// 三种方法
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]

感谢指正

CXGBro avatar Jan 12 '23 03:01 CXGBro

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;
}

bearki99 avatar Feb 12 '23 11:02 bearki99

function getMaxInArr(arr) {
  return arr.reduce((acc, cur) => acc > cur ? acc : cur)
}

vivipure avatar Mar 08 '23 14:03 vivipure

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)

MoYuanJun avatar Apr 03 '23 04:04 MoYuanJun

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));

KoEkko avatar Jul 12 '24 13:07 KoEkko

const getMax = (arr) => {
  return arr.reduce((a, b) => {return a > b ? a : b})
}; 

console.log(getMax([1, 2, 5, 4, 3]));

Windseek avatar Nov 14 '24 09:11 Windseek