introduce
I watched the telescope at home yesterday, saw the section on arrays, and mentioned an array method in ES6 Array.from()
, which is described in the book as follows:
The first argument to Array.from() is an array-like object, that is, any iterable structure.
from() is used to convert an array-like structure to an array instance...performs a shallow copy of an existing array
This is well understood, from() can convert Set
, Map
and Array
types and any iterable types into arrays. Object.assign()
Shallow copying is not difficult to understand. There is shallow copying of objects before , so it Array.from()
is not too much to have an array.
What interests me are the latter two parameters:
The second argument to Array.from() is an optional mapping function that augments the values of the new array without
Array.from().map()
creating an intermediate array as in the call.
Can also accept a third optional parameter to specifythis
the value in the mapping function
The overall syntax is this:
Array.from(arrayLike[, mapFn[, thisArg]])
So this method can be used to process array objects, and return a new array after processing the fields in each object. It sounds like a map()
replica of , but in fact, it is map()
the ancestor of .
It is not only used to deal with arrays, it has to deal with class arrays and arrays. As mentioned earlier, if you 类数组
use map(), you need to Array.from()
convert to an array before using map()
the method. Now Array.from() It directly saves you this step, which is equivalent to directly applying the function of map() to class arrays!
simple example
Use a function to modify the field name in the array object:
change this in the function to enhance the output!
This in the second function points to an object we customized, which is called in the function to process the elements of the array, and finally returns a new array!