-
-
Notifications
You must be signed in to change notification settings - Fork 229
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
数组中的最大值 #131
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); |
arr.sort()[arr.length - 1] 这种方法不能得到答案,sort函数需要指定排序函数才行。因为默认的排序函数是会将数组中的数据转化成字符串进行比较的,而字符串大小比较是根据字典序的(如:会出现 "11" < "2" 的情况) |
感谢指正 |
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;
} |
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
No description provided.
The text was updated successfully, but these errors were encountered: