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

JavaScript数组filter()方法会创建一个新数组,其中所有元素都通过了由提供的函数实现的测试。

以下是参数-

  • callback-测试数组中每个元素的函数。

  • thisObject-执行回调时用作此对象的对象。

您可以尝试运行以下代码来学习如何使用filter()JavaScript中的方法-

示例

<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>