JavaScript中(_, i) => expression含义及Array.from()参数疑问
(_, 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:
- The current element being processed in the array
- 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:
- The length is calculated as
(10-2)/2 +1 = 5, so we're creating an array of 5 elements. - For each index
ifrom 0 to 4:i=0:2 + 0*2 = 2i=1:2 +1*2=4i=2:2+2*2=6i=3:2+3*2=8i=4:2+4*2=10
- 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 initialundefinedelements; we just need the index to build our range values.
内容的提问来源于stack exchange,提问作者sevenDollars

