`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/en/docs/Web/JavaScript/Reference/Global_Objects/Array/from
我没有详细理解为什么会这样
I didn't understand in detail why this works
推荐答案
当 Javascript 检查一个方法是否可以被调用时,它使用 鸭打字.这意味着当你想从某个对象调用方法 foo
时,它应该是 bar
类型,然后它不会检查这个对象是否真的是 bar
但它检查它是否有方法 foo
.
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屋!