求數組最大值或最小值

來源:互聯網
上載者:User

標籤:const   取出   log   接收   ons   console   min   直接   his   

1. 一維數組

const arr = [1, 5, 9, 0, 11]const maxValue = Math.max.apply(null, arr )const minValue = Math.min.apply(null, arr )console.log(maxValue ,minValue)

 

2. 多維陣列

const arr1 = [2, 5, 8]const arr2 = [9, 5, 2]const convertArr = arr1.join(‘,‘).split(‘,‘)   // 轉為一維數組const maxValue = Math.max.apply(null, convertArr)const minValue = Math.min.apply(null, convertArr)

解釋一下為什麼可以通過apply這種方式來求最值,這是因為 

Math.max() 或  Math.min()方法不能接收一個數組為參數,我們要想直接求最值,只能這樣用:
const arr = Math.max(1, 5, 8, 2)console.log(arr)

所以我們就要把數組裡面的值一一取出來,這時就可以利用apply的特性,即接受數組為 非第一個參數, 再把原本的第一個this指向的參數置為null,就可以了

求數組最大值或最小值

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.