_.memoize()函數用於通過緩存該函數計算的結果來存儲給定函數。它用於加快運行緩慢的進程。
用法:
_.memoize(function, [hashFunction])
參數:此函數接受上述和以下描述的兩個參數:
- function:需要執行的函數。
- hashFunction:它是一個可選參數。 hashFunction用於計算用於存儲結果的哈希鍵。
返回值:它返回被調用函數的結果。
下麵的示例說明Underscore.js中的_.memoize函數:示例1:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src=
"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js">
</script>
</head>
<body>
<script type="text/javascript">
var fib = _.memoize(function (n) {
return n < 2 ? n:fib(n - 1) + fib(n - 2);
});
console.log(fib(15));
</script>
</body>
</html>
輸出:
範例2:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src=
"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js">
</script>
</head>
<body>
<script type="text/javascript">
var sum = _.memoize(function (n) {
return n < 1 ? n:n + sum(n - 1);
});
console.log('Sum of first 10 natural number:' + sum(10));
</script>
</body>
</html>
輸出:
相關用法
- p5.js tan()用法及代碼示例
- PHP pow( )用法及代碼示例
- CSS var()用法及代碼示例
- p5.js int()用法及代碼示例
- PHP dir()用法及代碼示例
- p5.js sin()用法及代碼示例
- PHP min( )用法及代碼示例
- PHP ord()用法及代碼示例
- p5.js str()用法及代碼示例
- PHP pos()用法及代碼示例
- PHP key()用法及代碼示例
- d3.js d3.set.has()用法及代碼示例
- d3.js now()用法及代碼示例
- d3.js d3.map.set()用法及代碼示例
- p5.js hex()用法及代碼示例
- p5.js arc()用法及代碼示例
注:本文由純淨天空篩選整理自AshokJaiswal大神的英文原創作品 Underscore.js | _.memoize() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。