Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...