當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


underscore.js _.before()用法及代碼示例

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>

輸出:




相關用法


注:本文由純淨天空篩選整理自tarun007大神的英文原創作品 Underscore.js _.before() function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。