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


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

_.isNull() 函數:

  • 它用於查找對象的值是否為空。
  • 如果對象具有空值,則輸出將為真,否則為假。
  • 我們甚至可以在這個函數中進行加法、減法等操作。

用法:

_.isNull(object)

參數:
它隻需要一個參數,即需要測試的對象。

返回值:
如果對象具有 null 值,則返回 true,否則返回 false。



例子:

1.在_.isNull()函數中傳遞一個數字:
_.isNull() 函數接受傳遞給它的參數,然後檢查對象是否具有空值。在這種情況下,由於值是定義的數字 “10”,所以輸出不為空。因此,輸出將是錯誤的。

HTML


<!-- 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(_.isNull(10));
    </script>
</body>
    
</html>

輸出:

2. 將 “null” 傳遞給 _.isNull() 函數:
因為這裏我們已經通過了 “null”,所以我們不需要檢查對象。我們知道傳遞給 _.isNull() 函數的值本身的值為 “null”。因此,輸出將為真。

HTML


<!-- 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(_.isNull(null));
    </script>
</body>
    
</html>

輸出:

3. 將 undefined” 傳遞給 _.isNull() 函數:
_.isNull() 函數接受傳遞給它的參數,這裏是 “undefined”。我們知道,如果有任何東西是未定義的,那麽它的值就是 null。因此,答案是正確的。



HTML


<!-- 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(_.isNull(undefined));
    </script>
</body>
    
</html>

輸出:

4、對_.isNull()函數的輸出進行操作:
首先,我們將上述兩個示例 (2, 3) 的輸出直接存儲在變量 a 和 b 中,然後我們對兩個結果進行了加法運算。最後,將其存儲在第三個變量中。由於 _.isNull() 的輸出在我們傳遞時為 false,在傳遞 null 時為 true,因此 false 存儲在 ‘a’ 變量中,true 存儲在 ‘b’ 變量中。現在,如果我們對兩個 ‘a’, ‘b’ 變量執行加法 (+) 操作,那麽我們將得到 true,因為 ‘b’ 為 true。因此 ‘c’ 變量將變為 1。

HTML


<!-- 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 = _.isNull(undefined);
        var b = _.isNull(null);
        var c = a + b;
        console.log(a);
        console.log(b);
        console.log(c);
    </script>
</body>
    
</html>

輸出:

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

鏈接如下:

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 _.isNull() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。