Prototype - Enumerable partition() 方法



此方法將元素劃分為兩組 -

  • 視為真。
  • 視為假。

預設情況下,使用常規 JavaScript 布林等價性,但可以提供一個計算元素的布林表示的迭代器。

與同時使用 findAll/select 和 reject 相比,這是一個更好的解決方案:它僅遍歷元素一次!

可選的 context 引數是迭代器函式將繫結到的引數。如果使用,則迭代器內部的 this 關鍵字將指向引數給出的物件。

語法

Iterator.partition([context]);

返回值

返回一個形式為 [[真值陣列],[假值陣列]] 的陣列。

示例

<html>
   <head>
      <title>Prototype examples</title>
      <script type = "text/javascript" src = "/javascript/prototype.js"></script>
      
      <script>
         function showResult() {
            var arr = ['hello', null, 42, false, true, , 17].partition();

            alert("Test 1 : " + arr.inspect() );
            // Returns [['hello', 42, true, 17], [null, false, undefined]]

            var arr = $R(1, 10).partition(function(n) {
               return 0 == n % 2;
            })

            alert("Test 2 : " + arr.inspect() );
            // Returns   [[2, 4, 6, 8, 10], [1, 3, 5, 7, 9]]
         }
      </script>
   </head>

   <body>
      <p>Click the button to see the result.</p>
      <br />
      <br />
      <input type = "button" value = "Result" onclick = "showResult();"/>
   </body>
</html>

輸出

prototype_enumerating.htm
廣告