PHP - Ds Deque::map() 函式



PHP 的Ds\Deque::map()函式用於獲取將回調函式應用於每個值的結果。

此函式用於將指定的回撥函式應用於雙端佇列的每個元素,並使用此函式獲得的結果更新雙端佇列。更新後的雙端佇列是此函式的輸出。

語法

以下是 PHP Ds\Deque::map() 函式的語法:

public Ds\Deque::map(callable $callback): Ds\Deque

引數

以下是此函式的引數:

  • callback - 一個返回要替換到新雙端佇列中的新值的函式。

返回值

此函式返回將回調函式應用於雙端佇列中每個值的結果。

示例 1

以下是 PHP Ds\Deque::map() 函式的基本示例:

<?php
   $deq = new \Ds\Deque([1,2,3,4,5]);
   echo "The original deque: \n";
   print_r($deq);
   echo "The updated deque: \n";
   print_r($deq->map(function($element) {
      return ($element+3)%2;
   }));
?>

輸出

執行上述程式後,將顯示以下輸出:

The original deque:
Ds\Deque Object
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)
The updated deque:
Ds\Deque Object
(
    [0] => 0
    [1] => 1
    [2] => 0
    [3] => 1
    [4] => 0
)

示例 2

以下是 PHP Ds\Deque::map() 函式的另一個示例。我們使用此函式來檢索將回調函式應用於此雙端佇列 ([74, 99, 177, 66, 198, 121, 154]) 中每個值的結果:

<?php
   $deq = new \Ds\Deque([74, 99, 177, 66, 198, 121, 154]);
   echo "The original deque: \n";
   print_r($deq);
   echo "The result of applying callback function: \n";
   print_r($deq->map(function($element) {
       return $element%11 ;
   }));
?>

輸出

上述程式產生以下輸出:

The original deque:
Ds\Deque Object
(
    [0] => 74
    [1] => 99
    [2] => 177
    [3] => 66
    [4] => 198
    [5] => 121
    [6] => 154
)
The result of applying callback function:
Ds\Deque Object
(
    [0] => 8
    [1] => 0
    [2] => 1
    [3] => 0
    [4] => 0
    [5] => 0
    [6] => 0
)
廣告