JavaScript 中 filter() 方法的作用是什麼?


JavaScript 陣列 filter() 方法建立一個包含所有透過指定函式實現的測試的元素的新陣列。

以下為其引數 -

  • 回撥 - 對陣列的每個元素進行測試的函式。

  • thisObject - 在執行回撥時用作 this 的物件。

你可以嘗試執行以下程式碼來了解如何在 JavaScript 中使用 filter() 方法 -

例項

線上演示

<html>
   <head>
      <title>JavaScript Array filter Method</title>
   </head>
   
   <body>
      <script>
         if (!Array.prototype.filter) {
            Array.prototype.filter = function(fun /*, thisp*/) {
               var len = this.length;

               if (typeof fun != "function")
               throw new TypeError();

               var res = new Array();
               var thisp = arguments[1];

               for (var i = 0; i < len; i++) {
                  if (i in this) {
                  var val = this[i]; // in case fun mutates this
                  if (fun.call(thisp, val, i, this))
                  res.push(val);
                  }
               }
               return res;
            };
         }
         function isBigEnough(element, index, array) {
            return (element >= 10);
         }

         var filtered = [12, 5, 8, 130, 44].filter(isBigEnough);
         document.write("Filtered Value : " + filtered );
      </script>
   </body>
   
</html>

更新於: 2019-07-30

216 次瀏覽

開啟你的職業生涯

完成課程以獲得認證

開始吧
廣告
© . All rights reserved.