2022-04-03 Learning record--JS-Two methods of turning array-like objects or iterable objects into arrays (Array.from() and [...array-like objects or iterable objects])

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,[...类数组对象或可迭代对象]

insert image description here

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, Mapand Set, and their prototype objects all implement the @@iteratormethod .)
    • To be an iterable, an object must implement @@iteratormethods . This means that the object (or some object on its prototype chain) must have @@iteratora , which can be accessed through the constant Symbol.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:
insert image description here

【Replenish】 ES6It is stipulated that the default Iteratorinterface deployed in the Symbol.iteratorproperties of the data structure, or, as long as a data structure has Symbol.iteratorproperties, 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']

Guess you like

Origin blog.csdn.net/weixin_48850734/article/details/123937832