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


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

_.range() 函數:

  • 它用於打印從作為參數給出的開始到結束也是一個參數的元素列表。
  • start 和 step 參數是可選的。
  • start 的默認值為 0,step 的默認值為 1。
  • 在形成的列表中,開始是包含的,而停止是排除的。
  • step 參數可以是正數也可以是負數。

用法:

_.range([start], stop, [step])

參數:
它需要三個參數:

  • start (optional)
  • stop
  • step (optional)

返回值:
返回值是從開始到結束的列表(不包括)。

例子:

  1. 僅將 stop 參數傳遞給 _.range() 函數:
    ._range() 函數將列表中的元素一個一個地取出,並對代碼進行指定的操作。像這裏的操作是添加列表的元素。添加所有元素後,reduce 函數結束。這裏memo的起始值取為‘0’。
    
    <!-- Write HTML code here -->
    <html>
       
    <head>
        <script src"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js" >
        </script>
    </head>
       
    <body>
        <script type="text/javascript">
            console.log(_.range(7));
        </script>
    </body>
       
    </html>

    輸出:

  2. 將 2 個參數傳遞給 _.range() 函數:
    我們甚至可以通過隻傳遞 2 個參數來使用這個函數,即 start 和 stop 參數,那麽它也不會出錯。和她一樣,起始參數是 7,它將包含在列表中。根據 _.range 函數,結束參數是 14,它不包含在列表中。因此,我們將采用 step 參數的默認參數,即 1。因此,我們將得到一個從 7 到 13 的列表。
    
    <!-- Write HTML code here -->
    <html>
       
    <head>
        <script src"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js" >
        </script>
    </head>
       
    <body>
        <script type="text/javascript">
            console.log(_.range(7, 14));
        </script>
    </body>
       
    </html>

    輸出:

  3. 將所有 3 個參數傳遞給 _.range() 函數:
    在這裏,我們采用所有 3 個參數,即提到了列表的開始、停止和步驟。因此,不需要默認值。這裏從 7 開始,步長為 3,這意味著 7 之後的元素將是列表中的 7+3=10。計算將以相同的方式繼續,直到 20 結束。
    
    <!-- Write HTML code here -->
    <html>
       
    <head>
        <script src"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js" >
        </script>
    </head>
       
    <body>
        <script type="text/javascript">
            console.log(_.range(7, 21, 3));
        </script>
    </body>
       
    </html>

    輸出:

  4. 將小於 start 參數的 stop 傳遞給 _.range() 函數:
    即使我們傳遞的 start 參數小於 stop 參數,_.range() 函數也不會報錯。它本身會將 step 參數調整為負值,以從給定的開始到達停止。因此,列表將包含從 21 到 16 的數字,因為末尾 15 不包含在列表中。
    
    <!-- Write HTML code here -->
    <html>
       
    <head>
        <script src"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js" >
        </script>
    </head>
       
    <body>
        <script type="text/javascript">
            console.log(_.range(21, 15));
        </script>
    </body>
       
    </html>

    輸出:

筆記:
這些命令在 Google 控製台或 Firefox 中不起作用,因為需要添加他們沒有添加的這些附加文件。
因此,將給定的鏈接添加到您的 HTML 文件中,然後運行它們。
鏈接如下:


<!-- Write HTML code here -->
<script type="text/javascript" 
src ="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js">
</script>

一個例子如下所示:




相關用法


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