javascript遍曆數組,針對數組中每一個元素執行fn函數,並將數組索引和元素作為參數傳遞

來源:互聯網
上載者:User

標籤:

遍曆主要有兩種方法,i++方法和in關鍵詞法

var list = [1, 2, 3, 4, 5, 6,7,8];//var l = list.length;for(var i in list) {    console.log(list[i]);}//[Finished in 0.3s]var list = [1, 2, 3, 4, 5, 6,7,8];//var l = list.length;for(var i = 0; i < list.length; i++) {    console.log(list[i]);}//[Finished in 0.5s]var list = [1, 2, 3, 4, 5, 6,7,8];var l = list.length;for(var i = 0; i < l; i++) {    console.log(list[i]);}//[Finished in 0.4s]

可見相對來說for in效率更高,故

function each(arr, fn) {    // your implement  for(index in arr){    fn(arr[index],index);  }}// 其中fn函數可以接受兩個參數:item和index// 使用樣本var arr = [‘java‘, ‘c‘, ‘php‘, ‘html‘];function output(item) {    console.log(item)}each(arr, output);  // java, c, php, html// 使用樣本var arr = [‘java‘, ‘c‘, ‘php‘, ‘html‘];function output(item, index) {    console.log(index + ‘: ‘ + item)}each(arr, output);  // 0:java, 1:c, 2:php, 3:html

不過實際輸出格式和期待有不同,仍待改進。

javascript遍曆數組,針對數組中每一個元素執行fn函數,並將數組索引和元素作為參數傳遞

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.