The difference between for-in and for-of

For-in is an ES5 standard that iterates over keys (arrays, objects, strings).

For-in is better for iterating over objects, because when a for-in iterates over a set of numbers, the order may not be in the order of the actual array. For-in iterates over all the attributes in the set that can be enumerated.

For-of is an ES6 standard that traverses values (arrays, objects, strings, maps, sets).

It is important to note that forEach traverses a set of numbers and cannot interrupt the loop using breack

The difference between the Set, Map, WeakSet, WeatMap

  • Set:
    • Members are unique, unordered and not repeated
    • Can be traversed, method: add,delete,has,clear property: size
  • WeatSet
    • Members are objects (weak references that can be reclaimed) and cannot hold values
    • The number of members in the weakSet object depends on whether the garbage collection mechanism is running or not, which can be used to store DOM nodes and is not prone to memory leaks
    • Cannot traverse, methods: add,delete,has
  • Map
    • It’s essentially a set of key-value pairs, sort of a set
    • It can be traversed by: set,get,has,delete,clear
    • Any data structure with an Iterator interface whose members are two-element arrays can be passed to Map
const m=new Map([["a",1],["b",2]])
Copy the code
  • WeatMap
    • Only accept objects as key names (except null)
    • The key name is a weak reference and the key value is arbitrary
    • Cannot traverse, methods get,set,has,delete

Use of the array sort method

  • Arrays are sorted on the original array, and no copies are made

  • No arguments are passed and sorted by character encoding order

  • Pass in the comparison function (a,b)=>val; A-b ascending, B-A descending