還記得jQuery支持鏈式調用嗎?
$('a').attr('target', '_blank') .append(' <i class="uk-icon-external-link"></i>') .click(function () {});
如果我們有一組操作,用underscore提供的函數,寫出來像這樣:
_.filter(_.map([1, 4, 9, 16, 25], Math.sqrt), x => x % 2 === 1);// [1, 3, 5]
能不能寫成鏈式調用?
能!
underscore提供了把對象包裝成能進行鏈式調用的方法,就是chain()函數:
_.chain([1, 4, 9, 16, 25]) .map(Math.sqrt) .filter(x => x % 2 === 1) .value();// [1, 3, 5]
因為每一步返回的都是包裝對象,所以最后一步的結果需要調用value()獲得最終結果。
小結
通過學習underscore,是不是對JavaScript的函數式編程又有了進一步的認識?
新聞熱點
疑難解答