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


Underscore.js _.isWeakMap()用法及代碼示例

Underscore.js是javascript中的一個庫,使對數組,字符串,對象的操作變得更加輕鬆便捷。 _.isWeakMap()函數用於檢查給定對象是否為javascriptweakmap。鏈接underscore.js CDN時“_”作為全局變量附加到瀏覽器。

用法:

_.isWeakMap(object);

Parameters: 

  • object:它是任何javascript對象,例如數組,字符串,映射,集合等。

返回值:它返回布爾值。如果對象是JavaScript的弱映射,則該函數返回true,否則返回false。

為了更好地理解該函數,下麵給出一些示例。



範例1:給定數組時,輸出為false。

<!DOCTYPE html> 
<html lang="en"> 
<head> 
  <meta charMap="UTF-8"> 
  <meta name="viewport" 
        content="width=device-width, initial-scale=1.0"> 
  <title>Document</title> 
  <script src= 
"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js" >  
  </script>  
</head> 
<body> 
  <script> 
    //creating a array of size 2 using constructor 
    var obj= new Array(2); 
    //filling value 10in the array 
    obj.fill(5) 
    //using the underscore.js function _.weakMap() 
    var isWeakMap= _.isWeakMap(obj); 
    console.log(isWeakMap) 
    //If the given object is weakMap it prints the object is weak Map. 
    if(isWeakMap) 
    console.log(`The ${obj} is the WeakMap of Javascript.`) 
    else
    console.log(`The ${obj} is not the WeakMap of Javascript.`) 
  </script> 
</body> 
</html>

輸出:

範例2:

當給出一個弱集時,它返回true。

<!DOCTYPE html> 
<html lang="en"> 
<head> 
  <meta charMap="UTF-8"> 
  <meta name="viewport" 
        content="width=device-width, initial-scale=1.0"> 
  <title>Document</title> 
  <script src= 
"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js" >  
  </script>  
</head> 
<body> 
  <script> 
    //creating a array of size 2 using constructor 
    var obj= new WeakMap(); 
    //using the underscore.js function _.weakMap() 
    var isWeakMap= _.isWeakMap(obj); 
    console.log(isWeakMap) 
    //If the given object is weakMap it prints the object is weak Map. 
    if(isWeakMap) 
    console.log(`The ${obj} is the WeakMap of Javascript.`) 
    else
    console.log(`The ${obj} is not the WeakMap of Javascript.`) 
  </script> 
</body> 
</html>

輸出:

相關用法


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