by @zhangbao(zhangbao) #0107
Note that “objects” are not strictly objects. Values of primitive types like strings are also called objects.
An overview of
- An iterable is an implementation
[Symbol.iterator]
Method property. - Class array objects have one
.length
Properties. - You can use
Array.from
Convert iterable and array-like objects into real arrays.
identify
Iterable and array-like objects are two very different concepts, so don’t confuse them.
- iterableIt means achieved
[Symbol.iterator]
Method property. - Array like objectIt has a
.length
Property, so it’s array-like.
For example, the following array-like object can be used without for… The of loop traverses.
// It is an array-like object because it has the length attribute
let arrayLike = {
0: "Hello".1: "World".length: 2
};
/ / an error! for... Of cannot iterate over objects that do not have the [symbol. iterator] attribute deployed
for (let item of arrayLike) {}
Copy the code
However, iterables and array-like objects are not mutually exclusive. For example, strings are both iterable objects (which can be used for… Of loops), again an array-like object.
But neither iterable nor array-like objects are true arrays, and therefore do not have array methods such as forEach, Map, filter, reduce, etc. This can sometimes be very inconvenient to manipulate objects, so how can we use array methods on these objects?
The answer is to use the array. from method.
Array.from
The magic of array. from is that it can convert any iterable or array-like object passed in to a real Array.
Two examples
Here’s an example:
See, arrayLike, when passed array. from, returns the real Array. This makes it easy to manipulate data using arrays.
Again, take the range variable from the article “Iterables” (below).
let range = {
from: 1.to: 5
}
range[Symbol.iterator] = function() {
return {
current: this.from,
last: this.to,
next() {
if (this.current <= this.last) {
return { done: false.value: this.current++ }
} else {
return { done: true }
}
}
}
}
Copy the code
Let’s do that with array. from.
The discovery was handled as usual.
Complete syntax
The entire syntax for the array. from method looks like this:
Array.from(obj[, mapFn, thisArg])
Copy the code
In addition to the first argument we used earlier, the object to be processed, the meanings of the other two optional arguments are:
mapFn
: The mapping function executed before each member is added to the final returned array.thisArg
: Specifies the mapping function execution contextthis
The value of the.
Here’s an example:
As you can see from the figure above, by pointing this in mapFn to thisArg, we change “apple” to “🍎” and “banana” to “🍌”, resulting in the final returned array [“🍎”, “🍌”].
Refer to the link
- Javascript. The info/iterable# ar…
(after)