javascript 找出数组的最大值和最小值的方法 (6种方法)
要有遥不可及的梦想,也要有脚踏实地的本事。----------- Grapefruit.Banuit Gang(香柚帮)求数组的最大值和最小值,方法还是挺多的,我会一一列举出来://首先我们声明一个不规则的数字数组var arr = [1,7,3,1,5,8,9,0,15,10,6,5];//第一种方法:// 最小值Array.prototype.min = function () {let mi
·
要有遥不可及的梦想,也要有脚踏实地的本事。----------- Grapefruit.Banuit Gang(香柚帮)
求数组的最大值和最小值,方法还是挺多的,我会一一列举出来:
//首先我们声明一个不规则的数字数组
var arr = [1,7,3,1,5,8,9,0,15,10,6,5];
//第一种方法:
// 最小值
Array.prototype.min = function () {
let min = this[0];
let len = this.length;
for (let i = 1; i < len; i++) {
if (this[i] < min) min = this[i]
}
return min
}
// 最大值
Array.prototype.max = function () {
let max = this[0];
let len = this.length;
for (let i = 1; i < len; i++) {
if (this[i] > max) max = this[i]
}
return max
}
// 结果
console.log(arr.min()); // 0
console.log(arr.max()); // 15
//第二种方法:
// 最小值
Array.min = function(array) {
return Math.min.apply(Math, array)
}
// 最大值
Array.max = function (array) {
return Math.max.apply(Math, array)
}
// 结果
console.log(Array.min(arr)); // 0
console.log(Array.max(arr)); // 15
//第三种方法:
// 最小值
Array.prototype.min = function() {
return Math.min.apply({}, this)
}
// 最大值
Array.prototype.max = function () {
return Math.max.apply({}, this)
}
// 结果
console.log(arr.min()); // 0
console.log(arr.max()); // 15
//第四种方法:
// 最小值
Array.prototype.min = function () {
return this.reduce((pre, cur) => {
return pre < cur ? pre : cur
})
}
// 最大值
Array.prototype.max = function () {
return this.reduce((pre, cur) => {
return pre > cur ? pre : cur
})
}
// 结果
console.log(arr.min()); // 0
console.log(arr.max()); // 15
//第五种方法:
let sortArr = arr.sort((a, b) => a - b)
// 最小值
sortArr[0]
// 最大值
sortArr[sortArr.length - 1]
// 结果
console.log(sortArr[0]); // 0
console.log(sortArr[sortArr.length - 1]); // 15
//第六种方法:
// 最小值
Math.min(...arr)
// 最大值
Math.max(...arr)
// 结果
console.log(Math.min(...arr)); // 0
console.log(Math.max(...arr)); // 15
就是这六种方法,已经全部列举出来了,希望能帮助到你吧!!!
更多推荐
已为社区贡献1条内容
所有评论(0)