查詢

Ds\Vector::apply()函式—用法及示例

「 對向量中的每個元素應用給定的回撥函式,並返回一個新的向量,其中包含回撥函式的返回值 」


函式名稱: Ds\Vector::apply()

函式概述: Ds\Vector::apply() 函式對向量中的每個元素應用給定的回撥函式,並返回一個新的向量,其中包含回撥函式的返回值。

函式簽名:

public function apply(callable $callback): Vector

引數:

  • $callback: 是一個可回撥函式,它將作用於向量中的每個元素。該回撥函式可以是一個閉包、一個函式名稱的字串或者一個物件方法的陣列。

返回值:

  • 返回一個新的 Ds\Vector 物件,其中包含回撥函式應用於原始向量中的每個元素的返回值。

注意事項:

  • 原始向量不受此函式的影響,保持不變。
  • 如果回撥函式對元素不進行修改,則返回的新向量與原始向量相同。

示例用法:

// 使用閉包
$vector = new Ds\Vector([1, 2, 3, 4]);
$newVector = $vector->apply(function($element) {
    return $element * 2;
});

print_r($newVector); // 輸出: Ds\Vector Object ([0] => 2 [1] => 4 [2] => 6 [3] => 8)

// 使用函式名稱的字串
function square($element) {
    return $element * $element;
}

$vector = new Ds\Vector([1, 2, 3, 4]);
$newVector = $vector->apply('square');

print_r($newVector); // 輸出: Ds\Vector Object ([0] => 1 [1] => 4 [2] => 9 [3] => 16)

// 使用物件方法的陣列
class MathOperations {
    public static function double($element) {
        return $element * 2;
    }
}

$vector = new Ds\Vector([1, 2, 3, 4]);
$newVector = $vector->apply([MathOperations::class, 'double']);

print_r($newVector); // 輸出: Ds\Vector Object ([0] => 2 [1] => 4 [2] => 6 [3] => 8)

以上示例演示瞭如何使用 Ds\Vector::apply() 函式。您可以使用閉包、函式名稱的字串或物件方法的陣列作為回撥函式,並使用該函式對向量中的每個元素進行處理,返回一個新的向量。

補充糾錯
上一個函式: Ds\Vector::capacity()函式
下一個函式: Ds\Vector::clear()函式
熱門PHP函式
分享連結