Iteratable object and class arrays

Climb up step by step 2021-09-15 08:21:48

Iteratable object

Realized Iterator Data structure of the interface , Deployed Symbol.Iterator object

Traverse
  • while loop

    /** ITERABLE Represents some kind of traversable data structure ,$iterator Is its iterator object .
    Each time the traverser object moves the pointer (next Method ), Check the return value done attribute , If the traversal is not over , Just move the pointer of the traverser object to the next step (next Method ), Keep cycling
    */
    var $iterator = ITERABLE[Symbol.iterator]();
    var $result = $iterator.next();
    while (!$result.done) {
     var x = $result.value;
     // ...
     $result = $iterator.next();
    }
     Copy code 
  • for...of

Convert to array
  • Extension operator

    Extension operator (...) For internal use for...of loop , So it can be used for iteratable objects

    let set = new Set().add('a').add('b').add('c');
    ['a', ...set, 'd'] // ["a", "a", "b", "c", "d"]
    ​
    let map = new Map().set('a', 1).set('b', 2);
    [...map] // [["a", 0], ["b", 1]]
     Copy code 
  • Array.from()

    Creates a new object similar to an array or iteratable object , Array instance of shallow copy

    let set = new Set().add('a').add('b').add('c');
    Array.from(set) // ["a", "b", "c"]
    ​
    let map = new Map().set('a', 1).set('b', 2);
    Arrary.from(map) // [["a", 0], [b", 1]]
     Copy code 

An array of class

There are numeric key names and length attribute

Traverse
Convert to array
  • Array.from(arrLike)

  • Array of slice Method + call/ apply

    let arrLike = {
     0: 'a',
     1: 'b',
     2: 'c',
     length: 3
    };
    ​
    // call change this The direction of
    Array.prototype.slice.call(arrLike)
    arrLike // ["a", "b", "c"]
    // perhaps
    [].slice.call(arrLike)
    arrLike // ["a", "b", "c"]
     Copy code 
Please bring the original link to reprint ,thank
Similar articles

2021-09-15