{hero}

reduce()

自 DataTables 1.10 起:

針對 API 結果集中的累加器和每個元素(從左到右)套用回呼函式。

說明

此方法可用於將結果集中的資料累加為單一值。一個很好的例子是加總資料欄中的值。Array reduce 方法(此方法以此為基礎)的更完整定義可在 Mozilla MDN 文件中找到關於 reduce 的說明

請注意,此方法中結果集中元素的遍歷是從左到右(即 0 到 length)。reduceRight() 可用於反向遍歷。

此方法利用了 DataTables API 物件是「類陣列」的事實,因為它們繼承了許多 JavaScript Array 類型的能力和方法。

在此情況下,此方法是 JavaScript Array.prototype.reduce 方法的代理,並作為 DataTables API 的實用方法提供。有關原始方法的更多資訊,請參閱 Mozilla MDN 文件中關於 reduce 的說明。在不原生支援 reduce 的瀏覽器中,會提供一個 polyfill,以使此 DataTables 方法能夠如預期般運作。

類型

function reduce( fn [, initialValue ] )

說明

針對 API 結果集中的累加器和每個元素套用回呼函式。

參數
傳回

任何

最後一次呼叫 fn 回呼函式所得的結果。

範例

加總欄中的資料

var table = new DataTable('#myTable');

var sum = table
	.column(0)
	.data()
	.reduce(function (a, b) {
		return a + b;
	});