underscore.js中的_.before()函數用於多次調用特定函數。它使用一個count變量來跟蹤該函數被調用的次數。
用法:
_.before(count, function)
參數:
- Count:這是一個函數被調用的次數。
- Function:它是運行計數時間的函數。
返回:此函數返回函數調用的計數。
注意:在通過代碼直接在瀏覽器中使用此代碼之前,請鏈接下劃線CDN。
範例1:
<!DOCTYPE html>
<html>
<head>
<script src =
"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js" >
</script>
</head>
<body>
<script>
let print=()=>{
console.log("geeks for geeks")
}
console.log(`Print function will only run 3 times`)
//the print function cannot run more than 3 times
count=_.before(4, print);
//calling count function more than 3 times
count();
count();
count();
count();
count();
count();
count();
</script>
</body>
</html>
輸出:
範例2:
從示例中可以明顯看出,如果一次又一次單擊按鈕,則打印函數將無法工作,因為它已經達到計數。
<!DOCTYPE html>
<html>
<head>
<script src =
"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js" >
</script>
</head>
<body>
<button id="btn">button</button>
<script>
let print=()=>{
console.log("geeks for geeks")
}
//the print function cannot run more than 99 times
count=_.before(100, print);
//calling count function more than 99 times
let btn=document.querySelector("#btn");
let run=()=>{
console.log(`Print function will only run 99 times`)
for(let i=0; i<5000; i++){
count()
}
}
btn.addEventListener("click", run)
</script>
</body>
</html>
輸出:
相關用法
- p5.js box()用法及代碼示例
- CSS hsl()用法及代碼示例
- d3.js d3.map.set()用法及代碼示例
- d3.js d3.set.has()用法及代碼示例
- PHP end()用法及代碼示例
- PHP each()用法及代碼示例
- p5.js nf()用法及代碼示例
- PHP Ds\Map get()用法及代碼示例
- PHP Ds\Set last()用法及代碼示例
- PHP pos()用法及代碼示例
- p5.js arc()用法及代碼示例
- PHP Ds\Set add()用法及代碼示例
- d3.js d3.hsl()用法及代碼示例
- d3.js d3.set.add()用法及代碼示例
- PHP key()用法及代碼示例
- PHP next()用法及代碼示例
注:本文由純淨天空篩選整理自tarun007大神的英文原創作品 Underscore.js _.before() function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。