Array.from({length:5},(v,i)=> i)`如何工作? [英] How does `Array.from({length: 5}, (v, i) => i)` work?
问题描述
我可能在这里遗漏了一些明显的东西,但是有人可以逐步解释为什么Array.from({length: 5}, (v, i) => i)
返回[0, 1, 2, 3, 4]
的原因吗?
I may be missing something obvious here but could someone breakdown step by step why Array.from({length: 5}, (v, i) => i)
returns [0, 1, 2, 3, 4]
?
https://developer.mozilla.org/zh_CN/docs/Web/JavaScript/Reference/Global_Objects/Array/from
我不明白为什么会这样
推荐答案
当Javascript检查是否可以调用方法时,它会使用鸭型.这意味着,当您想从某个对象(其类型为bar
)调用方法foo
时,它不会检查该对象是否真的为bar
,但会检查它是否具有方法
When Javascript checks if a method can be called, it uses duck-typing. That means when you want to call a method foo
from some object, which is supposed to be of type bar
, then it doesn't check if this object is really bar
but it checks if it has method foo
.
因此在JS中,可以执行以下操作:
So in JS, it's possible to do the following:
let fakeArray = {length:5};
fakeArray.length //5
let realArray = [1,2,3,4,5];
realArray.length //5
第一个类似于 fake javascript数组(具有属性length
).当Array.from
获得属性length
的值(在这种情况下为5)时,它将创建一个长度为5的实数组.
First one is like fake javascript array (which has property length
). When Array.from
gets a value of property length
(5 in this case), then it creates a real array with length 5.
这种 fakeArray 对象通常称为 arrayLike .
第二部分只是一个箭头函数,该函数使用索引值(第二个参数)填充数组.
The second part is just an arrow function which populates an array with values of indices (second argument).
此技术对于模拟某些对象进行测试非常有用.例如:
This technique is very useful for mocking some object for test. For example:
let ourFileReader = {}
ourFileReader.result = "someResult"
//ourFileReader will mock real FileReader
这篇关于Array.from({length:5},(v,i)=> i)`如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!