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

I may be missing something obvious here, but can someone Array.from({length: 5}, (v, i) => i)step by step, why Array.from({length: 5}, (v, i) => i)return [0, 1, 2, 3, 4]?

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/from

I did not understand in detail why this works

+13
source share
3 answers

When Javascript checks to see if a method can be called, it uses a duck . This means that when you want to call a method foofrom some object that must have a type bar, it does not check whether this object is really barbut checks if it has a method foo.

So in JS you can do the following:

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

The first one looks like a fake javascript array (which has lengthproperties). When it Array.fromgets the value of the property length(in Array.fromcase 5), it creates a real array of length 5.

This type of fakeArray object is often called arrayLike.

The second part is just an arrow function that populates the array with index values ​​(second argument).

This technique is very useful for mocking an object for testing. For instance:

let ourFileReader = {}
ourFileReader.result = "someResult"
//ourFileReader will mock real FileReader
+14

var arr1 = Array.from({
    length: 5 // Create 5 indexes with undefined values
  },
  function(v, k) { // Run a map function on said indexes using v(alue)[undefined] and k(ey)[0 to 4]
    return k; // Return k(ey) as value for this index
  }
);
console.log(arr1);
Hide result
+7

Nobody tells us on developer.mozilla.org about array.from that it mapFncan take 2 arguments, for example, vand k: v- the value of the current element, k- the index of the element. So here it is.

{length:5}create an object without any value, but with lengthequal 5;

(v, k) => k - an arrow function that assigns the serial number of the current element to this element value.

+3
source

Source: https://habr.com/ru/post/1660396/


All Articles