在 this question 中我遇到了以下简化的问题:
我们从一组具有值属性的对象开始。我们要计算每个值占值总和的百分比,并将其作为属性添加到结构中。为此,我们需要知道值的总和,但这个总和不是事先计算出来的。
//Original data structure
[
{ "value" : 123456 },
{ "value" : 12146 }
]
//Becomes
[
{
"value" : 123456,
"perc" : 0.9104
},
{
"value" : 12146 ,
"perc" : 0.0896
}
]
一个简单且可能最易读的解决方案是遍历数据结构两次。首先我们计算总和,然后计算百分比并将其添加到数据结构中。
var i;
var sum = 0;
for( i = 0; i < data.length; i++ ) {
sum += data[i].value;
}
for( i = 0; i < data.length; i++ ) {
data[i].perc = data[i].value / sum;
}
我们能否改为只遍历一次数据结构,并以某种方式告诉百分比表达式只应在知道整个总和后才计算?
我主要对解决纯 JavaScript 问题的答案感兴趣。即:没有任何库。
最佳答案
self-modifying code 的解决方案。
它将用于计算的函数 f
移动到迭代的末尾,然后它通过链式函数来分配单个项目的百分比。
var data = [
{ "value": 123456 },
{ "value": 12146 },
];
data.reduceRight(function (f, a, i) { // reduceRight, i=0 is at the end of reduce required
var t = f; // temporary save previous value or function
f = function (s) { // get a new function with sum as parameter
a.perc = a.value / s; // do the needed calc with sum at the end of reduce
t && t(s); // test & call the old func with sum as parameter
};
f.s = (t.s || 0) + a.value; // add value to sum and save sum in a property of f
i || f(f.s); // at the last iteration call f with sum as parameter
return f; // return the function
}, 0); // start w/ a value w/ a prop (undef/null don't work)
document.write('<pre>' + JSON.stringify(data, 0, 4) + '</pre>');
关于javascript - 纯javascript中的延迟分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34567287/