MDN 文档中的这个范围函数是如何工作的?

How does this range function from the MDN docs work?

MDN 文档描述了 Array.from() 语法;

// Arrow function
Array.from(arrayLike, (element) => { ... } )
Array.from(arrayLike, (element, index) => { ... } )
Array.from(arrayLike, (element, index, array) => { ... } )

它还提供了一个像这样的示例范围函数;

  const range = (start, stop, step) => Array.from({ length: (stop - start) / step + 1}, (_, i) => start + (i * step));

我试图准确理解这段代码的工作原理,但我对两件事感到困惑:

1.) { length: (stop - start) / step + 1} 在这里如何作为 arrayLike 对象发挥作用?这不会导致对象 {length: number} 吗?

2.) 作为索引传入的 (_, i) 中的 _ 是怎么回事?

{ length: (stop - start) / step + 1} 是“类似数组”的,因为它有一个 length 属性.

回调针对每个小于对象 length 的非负整数索引重复运行。对于每个索引,回调作为参数提供

  1. 输入对象上该索引处的任何值,并且
  2. 索引本身

我们不关心每个索引处的值(事实上,对象没有任何值),所以我们使用 _ 表示我们不关心这个参数。 (_在JavaScript中没有特殊意义,只是作者暗示“这是一个'blank',我们不关心它”的方式。我们只关心提供给 i 参数的索引,我们用它来计算该索引处的输出值。

  1. 一个类似数组的对象只有一个非负数length 属性。例如,Array.from({length: 2}) returns [undefined, undefined].

  2. _ 是映射回调的第一个参数(当前索引处的前一个元素)。它应该被忽略,因为没有先前指定的值。 i 是索引。
    映射回调将原始类数组对象的每个元素转换为输出中的新值。