询问范围函数的解释

Explanation Asked About a Range function

代码如下:

const range = (start, stop) =>
 new Array(stop - start).fill(0).map((v, i) => start + i);

停止-启动服务的目的是什么? (我猜数组的长度,但我不确定。实际上,我将其更改为加法,完全没有影响。)

.map((v,i)) 的参数有什么作用?

什么是参数“i”,如果我们一开始不打算使用它,为什么要传递“v”?

我知道 .fill() 用于填充数组的未定义索引,但也将不胜感激。

此函数获取两个给定参数之间的数字。

例子取自书本,不是我写的。这本书是关于 FP 的。

我想您已经很好地理解了此函数的大部分功能。我会先分解它,然后解决 3 个单独的问题。

什么范围:

  1. 确定要return的数字有多少:(stop - start)
  2. 创建该长度的数组:new Array(stop - start)
  3. 用占位符值填充数组 0.fill(0)
  4. 将数组循环到 return 所需值的新数组:.map(...)

您的问题

What purpose does stop - start serve? (I guess the length of array but I am not sure. In fact, I changed it to be an addition, and it affect nothing at all.)

您的猜测是正确的,但您检查猜测的方式可能是错误的。 唯一可以用加法代替减法的情况是 start 等于 0.

一些例子:

  • range(0, 2) -> [0, 1] -> 长度:2 - 0 = 2
  • range(2, 5) -> [2, 3, 4] -> 长度:5 - 2 = 3

What does the parameters of the .map((v,i)) do? What is parameter "i", and why did we pass "v" if we weren't going to use it in the first place?

map method on an array 将三个参数传递给您传递给它的函数:

  1. 数组的一个元素
  2. 那个值的索引
  3. 整个数组

大多数时候,您只需要第一个元素。例如:

[1, 2, 3].map(v => v * v) // [2, 4, 9]

但在这种情况下,您实际上对 索引 感兴趣,因为您可以使用它来创建一个范围,每个值都递增 1。

[0, 0, 0].map((v, i) => i) // [0, 1, 2]

即使未使用 v,您也必须使用占位符才能使用第二个参数。


I know that .fill() is for filling the undefined indexes of array but again an explanation about that would be appreciated as well.

当您使用 Array 构造函数创建具有给定长度的数组时,它将 return 一个包含“空洞”的数组。 map 将跳过这些漏洞。

要使用 map,您首先必须填补漏洞。

其他示例:

这里有 2 个替代 range 函数,可能有助于说明我提出的一些观点。

const range1 = (start, stop) =>
 new Array(stop - start)
  // Fill with the lower value of the range
  .fill(start)
  // and increment by the index of every element
  .map((x, i) => x + i);
  
  
const range2 = (start, stop) => Array
   // Use Array.from
  .from(
    // Your array with "holes" can go here
    Array(stop - start),
    // You can now skip the `fill` part
    (_, i) => start + i
  );