jQuery 的 $.map() 和 $.grep() 函式有什麼區別?


jQuery 的 map 函式將 jQuery 物件中的一組元素轉換為 jQuery 陣列中的另一組值,該陣列可能包含或不包含元素。grep() 函式用於查詢陣列中的元素。區別在於我們使用 $.grep 過濾陣列,使用 $.map 將函式應用於陣列中的每個專案。

jQuery map 函式

map 方法將 jQuery 物件中的一組元素轉換為 jQuery 陣列中的另一組值,該陣列可能包含或不包含元素。

以下是 jQuery.map() 方法的引數

  • callback − 在集合中的每個元素上執行的函式。

示例

您可以嘗試執行以下程式碼來學習如何使用 jQuery.map() 方法

線上演示

<html>

   <head>
      <title>jQuery Map Method</title>
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
       
      <script>
         $(document).ready(function(){
           
            var mappedItems = $("li").map(function (index) {
               var replacement = $("<li>").text($(this).text()).get(0);
               
               if (index == 0) {
                  // make the first item all caps
                  $(replacement).text($(replacement).text().toUpperCase());
               } else if (index == 1 || index == 3) {
                  // delete the second and fourth items
                  replacement = null;
               } else if (index == 2) {
                  // make two of the third item and add some text
                  replacement = [replacement,$("<li>").get(0)];
                  $(replacement[0]).append("<b> - A</b>");
                  $(replacement[1]).append("Extra <b> - B</b>");
               }

               // replacement will be an dom element, null,
               // or an array of dom elements
               return replacement;
            });
               
            $("#results").append(mappedItems);
         });
      </script>
       
      <style>
         body {
             font-size:18px;
         }
         ul {
             float:left;
             margin:0 30px;
             color:green;
             
         }
         #results {
            color:blue;
         }
      </style>
   </head>
   
   <body>

      <ul>
         <li>First</li>
         <li>Second</li>
         <li>Third</li>
         <li>Fourth</li>
         <li>Fifth</li>
      </ul>
       
      <ul id = "results">
      </ul>
       
   </body>
   
</html>

jQuery grep 函式

grep() 函式用於查詢陣列中的元素。

示例

您可以嘗試執行以下程式碼來學習如何使用 grep()

線上演示

<html>
<head>
  <title>jQuery grep() function</title>
  <style>
  div {
    color: blue;
  }
  p {
    color: red;
    margin: 0;
  }
  </style>
  <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
 
<div></div>
<p></p>

<script>
  var arr1 = [ 1, 7, 4, 8, 6, 1, 9, 5, 3, 7, 3, 8, 5, 8, 2 ];
  $( "div" ).text( arr1.join( ", " ) );
 
  arr1 = jQuery.grep(arr1, function( n, i ) {
    return ( n !== 5 && i > 6 );
  });
 
  $( "p" ).text( arr1.join( ", " ) );
</script>
 
</body>
</html>

更新於: 2019年12月17日

433 次瀏覽

開啟您的職業生涯

完成課程獲得認證

開始學習
廣告