了解箭头函数参数 [英] Understanding arrow function parameters
问题描述
我刚刚练习了一个标准的基本白板问题:创建一个由 0 到 n 的整数填充的数组.我的解决方案有效,但还有其他人发布了非常不寻常的语法.我真的很想理解它,但 MDN 文档对我帮助不大.我可以把 {length: n}
的工作原理放在一起,但是 (_, i) =>我
看起来很奇怪._
是未命名的函数,它接受 i
并返回 i
?但为什么会这样呢?我希望得到任何帮助.
I just practiced a standard basic whiteboard problem: Create an array filled with integers from 0 through n. My solution worked but there were others posted that had very unusual syntax. I am really trying to understand it but the MDN docs aren't helping me very much. I can put together how {length: n}
works but (_, i) => i
seems strange. _
is the unnamed function and it takes in i
and returns i
? but why is that there? I would love any help.
我的解决方案:
function arr(n){
var newArr = [];
for(var i = 0; i < n; i++){
newArr.push(i);
}
return newArr;
}
新的语法解决方案:
const arr = n => Array.from({length: n}, (_, i) => i);
推荐答案
映射器函数 Array.from
可以接受的第一个参数指示正在迭代的当前元素.也就是说,例如,从长度为 3
的类数组集合中,该参数将是 arrLike[0]
或 arrLike[1]
> 或 arrLike[2]
.
The first argument to the mapper function Array.from
can accept indicates the current element being iterated over. That is, from an array-like collection of length 3
, for example, that argument will be arrLike[0]
, or arrLike[1]
, or arrLike[2]
.
如果集合中那个点没有任何元素,比如这里,那么访问这些索引将返回undefined
:
If there aren't any elements at that point in the collection, like here, then accessing those indicies will return undefined
:
const arr = n => Array.from({length: n}, (_, i) => {
console.log(_);
return i;
});
arr(3);
下划线只是一个变量名.您可以随意定义它.未使用的参数被称为_
是一个常见的约定,但这只是一个约定,而不是语法规则.
The underscore is just a variable name. You can define it however you want. It's a common convention for an unused argument to be called _
, but it's only a convention, not a syntax rule.
由于映射器函数只关心当前的索引被迭代以构建新数组,因此它定义了第二个参数i
,然后立即返回它.(Array.from
可以迭代具有 length
属性的任何对象,从 0
到 length - 1
.即使如果对象上实际上不存在这些属性,则第二个参数 index 仍将从 0 递增到 length - 1
.)
Since the mapper function only cares about the current index being iterated over in order to construct the new array, it defines the second argument i
and then returns it immediately. (Array.from
can iterate over any object with a length
property, from 0
to length - 1
. Even if none of those properties actually exist on the object, the index, the second argument, will still be incremented from 0 up to length - 1
.)
这篇关于了解箭头函数参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!