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


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

_.isUndefined()函數:

  • 它檢查傳遞給它的參數是否未定義。
  • 如果傳遞的參數未定義,則返回 true,否則返回 false。
  • 我們甚至可以將窗口元素傳遞給它。

用法:

_.isUndefined(value)

參數:
它隻需要一個參數,即需要檢查的值或變量。

返回值:
如果傳遞的值或參數未定義,則返回 true,否則返回 false。

例子:

  1. 將變量傳遞給 _.isUndefined() 函數:
    _.isUndefined() 函數接受傳遞給它的參數。因此,這裏它將檢查傳遞的變量‘a’。由於‘a’的值之前被定義為10,所以它是一個已定義的變量。因此,輸出將為假。
    
    <!-- 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"> 
            var a=10; 
            console.log(_.isUndefined(a)); 
        </script> 
    </body> 
        
    </html> 

    輸出:

  2. 將數字傳遞給 _.isUndefined() 函數:
    如果我們將一個數字傳遞給 _.isUndefined() 函數,那麽它會檢查該數字是否未定義。因為我們知道所有數字都已定義。因此,答案將是錯誤的。
    
    <!-- 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(_.isUndefined(10)); 
        </script> 
    </body> 
        
    </html> 

    輸出:

  3. 將 “undefined” 傳遞給 _.isUndefined() 函數:
    _.isUndefined() 函數獲取傳遞給它的元素,這裏是“undefined”。由於傳遞的參數未定義,因此輸出將為 true。
    
    <!-- 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(_.isUndefined(undefined)); 
        </script> 
    </body> 
        
    </html> 

    輸出:

  4. 將missingVariable傳遞給_.isUndefined()函數:
    這裏我們將“window.missingVariable”作為參數傳遞。但這裏我們沒有定義任何變量。所以丟失的變量沒有值。因此,它是未定義的。輸出結果為真。
    
    <!-- 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(_.isUndefined(window.missingVariable)); 
        </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 _.isUndefined() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。