这里的一个功能的方法,因此需要ES5:
var w = a.unzip(3).map(function(v, i, a) {
var weight = v[0] * v[1];
var sum = weight * v[2];
return [sum, weight];
}).reduce(function(p, c, i, a) {
return [p[0] + c[0], p[1] + c[1]];
}, [0, 0]);
var aw = w[0]/w[1];
其中在伪代码是:
split the array into chunks of three
convert each three [p1, p2, x ] into a pair [ p1 * p2 * x , p1 * p2 ]
sum the pairs (along the array, not within each pair)
divide one by the other
,并且其中(非标准)unzip
函数组块阵列:
Object.defineProperty(Array.prototype, 'unzip', {
value: function(n) {
n = n || 2;
return this.reduce(function(p, c, i, a) {
if (i % n === 0) {
p.push(a.slice(i, i + n));
}
return p;
}, []);
}
});
您能给出示例值吗? 向我们展示一个具有真实世界值的计算结果,并且您期望 – Tschallacka 2012-08-08 14:38:56
的结果是否必须让您的'p'和'x'值以这种方式交错? – Alnitak 2012-08-08 14:39:12
你在x之前总是有2 p还是可以改变? – Youssef 2012-08-08 14:41:04