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


i may missing obvious here breakdown step step why array.from({length: 5}, (v, k) => k) 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 works

javascript uses duck-typing. means when call method foo object, supposed of type bar doesn't check if object bar checks if has method foo.

to sum up:

let fakearray = {length:5}; fakearray.length //5 let realarray = [1,2,3,4,5]; realarray.length //5 

first 1 "fake" javascript array (which has property length). when array.from checks property length returns 5 , therefore creates real array length 5. can call fakearray object "arraylike".

second part lamba populates array values of indices (second argument).

this technique useful mocking object test. example:

let ourfilereader = {} ourfilereader.result = "someresult" //ourfilereader mock real filereader 

Comments

Popular posts from this blog

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -