基礎(chǔ)的通過(guò)for循環(huán)假設(shè)一個(gè)最大值或者最小值這種方法就不說(shuō)了
今天要說(shuō)一種通過(guò)apply來(lái)實(shí)現(xiàn)拿到數(shù)組中最大值和最小值
數(shù)組中并沒(méi)有提供arr.max()和arr.min()這樣的方法。可是JavaScript提供了這樣一個(gè)這樣的內(nèi)置函數(shù)Math.max()和Math.min()方法:
對(duì)于純數(shù)字?jǐn)?shù)組悠就,可以使用JavaScript中的內(nèi)置函數(shù)Math.max()和Math.min()方法,使用這兩個(gè)內(nèi)置函數(shù)可以分別找出數(shù)組中最大值和最小值,在使用之前先溫習(xí)一下Math.max()和Math.min()這兩個(gè)函數(shù):
Math.max()函數(shù)返回一組數(shù)中的最大值菇民。
Math.max(5,10); // 10
Math.min()和Math.max()剛好相反尽楔,會(huì)返回一組數(shù)中的最小值
Math.min(5,10); // 5
這些函數(shù)如果沒(méi)有參數(shù),則結(jié)果為 -Infinity;如果有任一參數(shù)不能被轉(zhuǎn)換為數(shù)值第练,則結(jié)果為NaN阔馋。最主要的是這兩個(gè)函數(shù)對(duì)于,數(shù)字組成的數(shù)組是不能直接使用的。但是娇掏,這有一些類似地方法呕寝。
Function.prototype.apply()讓你可以使用提供的this來(lái)調(diào)用參數(shù)。
<script>
// 取數(shù)組中的最大值
Array.max = function (array) {
return Math.max.apply(Math, array)
}
// 取數(shù)組中的最小值
Array.min = function (array) {
return Math.min.apply(Math, array)
}
var arr = [1, 2, 3, 4, 5, 6, 7];
console.log(Array.max(arr)) // 7
console.log(Array.min(arr)) // 1
</script>