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.