javascript 使用 ECMASCRIPT 6 Generator/Functions 对数组求和的最佳方法是什么
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31229853/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the best way to sum arrays using ECMASCRIPT 6 Generator/Functions
提问by Blauharley
Is there a better way instead of adding values of arrays up using a generator function as closure?
有没有更好的方法而不是使用生成器函数作为闭包来添加数组的值?
var sumArrays = function(){
var sum = 0;
return function*(){
while(true){
var array = yield sum;
if(array.__proto__.constructor === Array){
sum += array.reduce(function(val,val2){ return val+val2; });
}
else sum=0;
}
};
};
var gen = sumArrays();
// is this step required to make a generator or could it be done at least differently to spare yourself from doing this step?
gen = gen();
// sum some values of arrays up
console.log('sum: ',gen.next()); // Object { value=0, done=false}
console.log('sum: ',gen.next([1,2,3,4])); // Object { value=10, done=false}
console.log('sum: ',gen.next([6,7])); // Object { value=23, done=false}
// reset values
console.log('sum: ',gen.next(false)); // Object { value=0, done=false}
console.log('sum: ',gen.next([5])); // Object { value=5, done=false}
回答by Felix Kling
This doesn't seem to be a problem generators are supposed to solve, so I would not use a generator here.
这似乎不是生成器应该解决的问题,所以我不会在这里使用生成器。
Directly using reduce
(ES5) seems to be more appropriate:
直接使用reduce
(ES5)似乎更合适:
let sum = [1,2,3,4].reduce((sum, x) => sum + x);
As a function:
作为一个函数:
function sum(arr) {
return arr.reduce((sum, x) => sum + x);
}
If you really want to sum multiple arrays across multiple function calls, then return a normal function:
如果您真的想对多个函数调用中的多个数组求和,则返回一个普通函数:
function getArraySummation() {
let total = 0;
let reducer = (sum, x) => sum + x;
return arr => total + arr.reduce(reducer);
}
let sum = getArraySummation();
console.log('sum:', sum([1,2,3])); // sum: 6
console.log('sum:', sum([4,5,6])); // sum: 15
Keep it simple.
把事情简单化。