reduceメソッドを使った、配列の合計値の求め方。
var array = [1, 10, 100]
array.reduce(function(a, b){ return a + b })
-> 111
配列の内容がオブジェクトで、特定の項目の合計値を求めたい場合は、return でオブジェクトを返す必要がある。
var array = [{value:1},{value:10},{value:100}]
array.reduce(function(a,b){ return a.value + b.value }) //error
-> NaN
array.reduce(function(a,b){ return { value:a.value + b.value } })
-> Object {value: 111}
例)任意の要素の横幅(width値)を取得し、その合計値を返す。
Array.prototype.slice.call(document.querySelectorAll(".testElement"))
.reduce(function(a,b){
return { clientWidth:a.clientWidth + b.clientWidth }
})
-> Object {clientWidth: 1144}