带有JavaScript中的累加器的数组映射 [英] Array map with accumulator in JavaScript

查看:47
本文介绍了带有JavaScript中的累加器的数组映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在累加器中使用数组映射?

How to use Array map with accumulator?

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

Lets have a list of numbers and find a list of current sums. Example:

const nums = [1, 1, 1, -1, -1];
const sums = [1, 2, 3,  2,  1];

我尝试通过在 thisArg 中使用累加器来对 map 进行处理,原因是根据:

I try to do it with map, by using accumulator in a thisArg because according to: MDN Array.prototype.map()

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

thisArg - value to use as this when executing callback.

我提供的对象的 acc 设置为 0 作为 thisArg :

I provide an object with acc set to 0 as 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 ]

测试通过外部累加器通过

The test passes with an external accumulator:

let   acc    = 0;
const actual = nums.map(val => acc += val);

推荐答案

使用箭头功能,则您松了

With using arrow functions, you loose this in the function, which is already set from the outer space.

您可以使用功能声明 thisArg .

const nums = [1, 1, 1, -1, -1];
const actual = nums.map(function (val) { return this.acc += val; }, { acc: 0 });

console.log(actual);

要保留箭头功能,可以使用闭包通过累加器,

For keeping a arrow function, you could use a closure over the accumulator,

(acc => val => acc += val)(0)  // complete closure with callback

分两步工作,首先它直接使用 acc

which works in two steps, first it calls the function directly with a value for acc

(acc =>                  )(0)  // function for generating a closure over acc

并返回内部函数作为 Array#map

and returns the inner function as a callback for Array#map

        val => acc += val      // final callback

加上 acc 的闭包,这意味着 acc 的范围在自己的函数内部,并且在返回的回调内部.

with a closure over acc, that means the scope of acc is inside of the own function and inside of the returned callback.

const nums = [1, 1, 1, -1, -1];
const actual = nums.map((acc => val => acc += val)(0));

console.log(actual);

这篇关于带有JavaScript中的累加器的数组映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆