Array.from vs Array.prototype.map

What is the difference between these two functions?

They both create a new Array object. The only difference I've found so far is that Array.from supports ArrayLike parameters. I see no reason why they simply did not add ArrayLike support for the Array.prototype.map function.

Did I miss something?

+5
source share
3 answers

The purpose of Array.from() is to take an object that does not contain an array (but looks like an array) and make a copy of it in a real array. Then it allows you to use all the array methods on the copy, including things that go beyond repeating them, such as .splice() , .sort() , .push() , .pop() , etc ..., which are obviously much more capable than just doing .map() working with arrays.

+7
source

Creating Array.prototype of a prototype object for each individual array of type "Class" in JS (more importantly, in the DOM, where most objects of type "array" live). Possible error.

What will .reduce( ) look like in the list of HTML elements / attributes?

Array.from is the official version of [].slice.call(arrayLike); with the added benefit: you don't need to create an unused array, just to create an array.

Thus, Array.from can be populated with function (arrLike) { return [].slice.call(arrLike); } function (arrLike) { return [].slice.call(arrLike); } , and minus the built-in speed / memory changes, this is the same result.

This has nothing to do with the map | reduce | filter | some | every | find, which are the keys to living a long and happy life, without the need for micromanipulation to get things done.

+1
source

Array.map looks a little more productive:

 var a = () => [{"count": 3},{"count": 4},{"count": 5}].map(item => item.count); var b = () => Array.from([{"count": 3},{"count": 4},{"count": 5}], x => x.count); var iterations = 1000000; console.time('Function #1'); for(var i = 0; i < iterations; i++ ){ b(); }; console.timeEnd('Function #1') console.time('Function #2'); for(var i = 0; i < iterations; i++ ){ a(); }; console.timeEnd('Function #2') 

Running this code using Chrome (version 65.0.3325.181) on this page gave me the following results:

 Function #1: 520.591064453125ms Function #2: 33.622802734375ms 
0
source

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


All Articles