JavaScript中带累加器的数组映射

JavaScript中带累加器的数组映射,javascript,dictionary,Javascript,Dictionary,如何使用带累加器的数组映射 让我们有一个数字列表,并找到当前总和的列表。 例如: 我尝试使用map,在thisArg中使用累加器,因为根据: thisArg-执行回调时用作this的值 我将acc设置为0的对象作为thisArg: const actual = nums.map(val => this.acc += val, {acc: 0}); require('assert').deepEqual(actual, sums); 它因错误而崩溃: AssertionError: [

如何使用带累加器的数组映射

让我们有一个数字列表,并找到当前总和的列表。 例如:

我尝试使用
map
,在
thisArg
中使用累加器,因为根据:

thisArg
-执行回调时用作
this
的值

我将
acc
设置为
0
的对象作为
thisArg

const actual = nums.map(val => this.acc += val, {acc: 0});

require('assert').deepEqual(actual, sums);
它因错误而崩溃:

AssertionError: [ 1, 2, 3, 2, 1 ] deepEqual [ NaN, NaN, NaN, NaN, NaN ]
使用外部蓄能器通过测试:

let   acc    = 0;
const actual = nums.map(val => acc += val);
使用时,您将在函数中释放,该函数已从外部空间设置

您可以使用
thisArg

constnums=[1,1,1,-1,-1];
const-actual=nums.map(函数(val){返回this.acc+=val;},{acc:0});

控制台日志(实际)您可以使用
Array.prototype.reduce()
。 这将不需要您为arrow函数创建额外的闭包,并提供累加器作为常规参数

constnums=[1,1,1,-1,-1]
常量实际值=nums.reduce(
(acc,val)=>(acc.push((acc[acc.length-1]| | 0)+val),acc),[]
)

console.log(实际)/[1,2,3,2,1]
您看过Array.reduce吗?尝试使用reduce函数,而不是off-map。它支持开箱即用的累加器。如何使用
reduce
nums.reduce((acc,val)=>acc.push(acc.last+val),[0])
失败。原因是没有
数组。last
。您需要
acc[i]
acc[acc.length-1]
来指出这种绑定的不足,但更好地展示了使用箭头函数创建闭包的简单性。如果您通过迭代项将数组“扫描”到另一个相同大小的数组,这种Haskell式方法非常好。很好的图案。这是一个很酷的图案,解释得很好,非常感谢
let   acc    = 0;
const actual = nums.map(val => acc += val);