1. Two ways to turn array-like objects or iterable objects into arrays
Two ways to turn array-like or iterable objects into arrays:
- method 1,
Array.from(类数组对象或可迭代对象)
- Method 2,
[...类数组对象或可迭代对象]
Second, what is an array-like object or an iterable object?
The brain-loving little radish must want to ask: That. . . What is an array-like object or an iterable object?
- Array-like/pseudo-array objects (similar to arrays, but don't have any array properties other than
length属性
and . Like etc.)索引元素
arguments
- Iterable objects (Currently all built-in iterable objects are as follows:
String
,Array
,TypedArray
,Map
andSet
, and their prototype objects all implement the@@iterator
method .)
- To be an iterable, an object must implement
@@iterator
methods . This means that the object (or some object on its prototype chain) must have@@iterator
a , which can be accessed through the constantSymbol.iterator
, as shown in the following table [referenced from MDN ]:
Attributes | value |
---|---|
[Symbol.iterator] | A parameterless function whose return value is an object conforming to the iterator protocol. |
For example Set
:
【Replenish】
ES6
It is stipulated that the defaultIterator
interface deployed in theSymbol.iterator
properties of the data structure, or, as long as a data structure hasSymbol.iterator
properties, it can be considered as "traversable/iterable" (iterable
). [referenced from ES6 ]
3. Examples
1. Generate an array from an array-like object (arguments)
arguments is an array-like object corresponding to the arguments passed to the function.
function fn() {
// 方法1
return Array.from(arguments);
// 方法2
return [...arguments];
}
fn(1, 2, 3); // [1,2,3]
1. Generate an array from String
// 方法1
console.log(Array.from('carrot')); // ['c', 'a', 'r', 'r', 'o', 't']
// 方法2
console.log([...'carrot']); // ['c', 'a', 'r', 'r', 'o', 't']
2. Generate an array from Set
// new Set(数组):实现数组去重
const set = new Set(['a','b','c','a','d','c']); // {'a', 'b', 'c', 'd'}
// 方法1
console.log(Array.from(set)); // ['a', 'b', 'c', 'd']
// 方法2
console.log([...set]); // ['a', 'b', 'c', 'd']
3. Generate an array from a Map
const map = new Map([[1, 2], [2, 4], [4, 8]]);
// 方法1
Array.from(map); // [[1, 2], [2, 4], [4, 8]]
// 方法2
[...map]; // [[1, 2], [2, 4], [4, 8]]
const mapper = new Map([['1', 'a'], ['2', 'b']]);
// 方法1
Array.from(mapper.values()); // ['a', 'b']
Array.from(mapper.keys()); // ['1', '2']
// 方法2
[...mapper.values()]; // ['a', 'b']
[...mapper.keys()]; // ['1', '2']