Javascript實現ECMAScript 5中的map、reduce和filter函數

來源:互聯網
上載者:User
    // 最基礎的forEach    function forEach(array, action) {        for (var i = 0; i < array.length; i++) {            action(array[i]);        }    }    // 測試forEach    forEach(["Pear", "Apple"], function(name) {        console.log(name);    });    // ------------------------------------------------ //    // 實現reduce    function reduce(combine, base, array) {        forEach(array, function(element) {            base = combine(base, element);        });        return base;    }    // 使用reduce執行個體1:計算數組中的0的個數    function countZeros(array) {        function counter(total, elem) {            return total + (elem == 0 ? 1 : 0);        }        return reduce(counter, 0, array);    }    alert("countZeros by reduce: " + countZeros([1, 3, 0, 4, 7, 0]));    // 使用reduce執行個體2:求和    function sum(array) {        function add(a, b) {            return a + b;        }        return reduce(add, 0, array);    }    alert("sum by reduce: " + sum([1, 2, 3, 5]));    // ------------------------------------------------ //    // 實現map    function map(func, array) {        var result = [];        forEach(array, function(elem) {            result.push(func(elem));            // 對於map,func函數一般只有一個參數,所以用func(elem)        });        return result;    }    // 利用map實現數組的每個數字翻倍    var array = [1, 2, 3, 4, 5];    var mappedArray = map(function(elem) {        return elem * 2;    }, array);    console.log(mappedArray);    // 利用map實現數組向下取整    var array2 = [1.3, 4.5, 6.7, 8, 9.2];    var mappedArray2 = map(Math.floor, array2);    console.log(mappedArray2);    // ------------------------------------------------ //        // 實現filter:    function filter(func, array) {        var result = [];        forEach(array, function(elem) {            if(func(elem))                result.push(elem);        });                return result;    }        // 使用filter過濾出偶數    function isEven(elem) {        return elem % 2 == 0;    }    var array3 = [1, 2, 3, 4, 5, 6, 7, 8, 9];    var filterArray = filter(isEven, array3);    console.log(filterArray);    

 

相關文章

聯繫我們

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