[英]Reduce function execution - Can anyone help me in identifying the error as I am unable get the result
const sum = (arr) => { arr.reduce((acc, val) => { return acc = acc + val; }, 0); }; console.log(sum([2, 3, 4, 5]));
You have to return the result of the call to reduce
in your sum
method.您必须在
sum
方法中返回调用结果以reduce
。
Also, in the reduce
method you are returning the result of assigning a value.此外,在
reduce
方法中,您将返回分配值的结果。 Returning the result of an assignment can be confusing and there is no need for that in this case.返回分配的结果可能会令人困惑,在这种情况下不需要这样做。
Having all that in mind, your code should look:考虑到所有这些,您的代码应如下所示:
const sum = arr => arr.reduce((acc, val) => acc + val, 0); console.log(sum([2, 3, 4, 5]));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.