Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
145 views
in Technique[技术] by (71.8m points)

javascript - How does `Array.from({length: 5}, (v, i) => i)` work?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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

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.

This kind of fakeArray object is often called 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...