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


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


Underscore.js是javascript中的一個庫,使對數組,字符串,對象的操作變得更加輕鬆便捷。 _.isMap()函數用於檢查給定的對象是否為javascript Map。

注意:在瀏覽器中使用下劃線函數之前,非常有必要鏈接下劃線CDN。鏈接underscore.js CDN時“_”作為全局變量附加到瀏覽器。

用法:

_.isMap(object);

Parameters: 

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

返回值:它返回布爾值。如果對象是javascript的Map,則該函數返回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 array with value 10 
    obj.fill(10); 
    //using the underscore.js function _.isMap() 
    var isMap= _.isMap(obj); 
    console.log(isMap) 
    //If the given object is Map it prints the object is Map. 
    if(isMap) 
    console.log(`The ${obj} is the Map of Javascript.`) 
    else 
    console.log(`The ${obj} is not the Map of Javascript.`) 
  </script> 
</body> 
</html>

輸出:

範例2:

給出Map後,它將返回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 Map using constructor 
    var obj= new Map(); 
    //using the underscore.js function _.isMap() 
    var isMap= _.isMap(obj); 
    console.log(isMap) 
    //If the given object is Map it prints the object is Map. 
    if(isMap) 
    console.log(`The ${obj} is the Map of Javascript.`) 
    else 
    console.log(`The ${obj} is not the Map of Javascript.`) 
  </script> 
</body> 
</html>

輸出:

範例3:

給對象作為參數時,輸出為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 Javascript Object using constructor 
    var obj= new Object(); 
    obj={ 
      "a":1, 
      "b":2 
    } 
    //using the underscore.js function _.isMap() 
    var isMap= _.isMap(obj); 
    console.log(isMap) 
    //If the given object is Map it prints the object is Map. 
    if(isMap) 
    console.log(`The ${obj} is the Map of Javascript.`) 
    else 
    console.log(`The ${obj} is not the Map of Javascript.`) 
  </script> 
</body> 
</html>

輸出:

相關用法


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