You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript中(_, i) => expression含义及Array.from()参数疑问

Understanding (_, i) => expression in JavaScript and Its Use in Array.from()

Great question! Let's break this down clearly so you can see exactly what's going on here.

First: What's the role of the second argument in Array.from()?

Array.from() accepts an optional second parameter — a mapping function that runs for every element being created in the new array. This function takes two standard arguments:

  1. The current element being processed in the array
  2. The index of that element

So why use (_, i) as the parameters?

The underscore _ is just a convention in JavaScript (and many other languages) for a variable we don't need to use.

In the range function example:

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

We're creating an array from an object with a length property — this means every "element" in the initial array-like object is undefined. We don't care about those undefined values at all; we only need the index i to calculate the actual value we want (which is start + i * step).

Using _ tells anyone reading the code: "I know this parameter exists, but I'm not going to use it here." It also prevents linters from throwing warnings about unused variables, which is a nice bonus.

What does (_, i) => expression mean exactly?

This is an arrow function where:

  • The first parameter (_) is ignored (we don't reference it anywhere in the function body)
  • The second parameter (i) is used to compute the return value (start + i * step)

Let's take a concrete example to make it real. If we call range(2, 10, 2), here's what happens:

  1. The length is calculated as (10-2)/2 +1 = 5, so we're creating an array of 5 elements.
  2. For each index i from 0 to 4:
    • i=0: 2 + 0*2 = 2
    • i=1: 2 +1*2=4
    • i=2: 2+2*2=6
    • i=3: 2+3*2=8
    • i=4: 2+4*2=10
  3. The final array is [2,4,6,8,10] — exactly what we'd expect from a range function!

To sum up

  • _ is a placeholder for an unused parameter — it's a convention, not a special JavaScript syntax.
  • (_, i) => ... is an arrow function that only cares about the second parameter (the index) and ignores the first.
  • In this Array.from() use case, it's perfect because we don't need the initial undefined elements; we just need the index to build our range values.

内容的提问来源于stack exchange,提问作者sevenDollars

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 00:08:13