The preface

Following on from the previous chapter on basic reference types, this chapter notes collection reference types. Collection reference types include object, array and stereotype array, Map, WeakMap, Set, WeakSet. The stereotyped arrays are only covered in the first section of “Animation and Canvas Graphics (Chapter 18)” and “JavaScript apis for Chapter 20” (which I have seen so far), so it is recommended to save them for later and will not affect most of the rest of this chapter and beyond.

MIND

Object

The Object type is the most common, and examples are suitable for storing and exchanging data between applications. See Chapter 8 for details.

create

First, use constructors

let obj = new Object(a); obj.name ='JayeZhu';
Copy the code

The second option, using object literals, is more recommended

let obj = { name: 'JayeZhu' };
Copy the code

Using this approach, it should be noted that numeric attributes are automatically converted to strings

const obj = { 1: 1 };
console.log(obj['1']); / / 1
Copy the code

access

Obj [‘name’]; obj[‘name’]; obj[‘name’]; obj[‘name’]

  • Brackets allow variable access to properties
    let obj = { name: 'JayeZhu' };
    const key = 'name';
    console.log(obj[key]); // 'JayeZhu'
    Copy the code
  • If the attribute name contains a character that causes a syntax error, or contains a keyword/reserved word, use brackets
  • Attribute names contain non-alphanumeric characters and use brackets

While brackets are great, dot reading is an object-oriented convention and is more recommended

Array

Array is also extremely common. An Array instance is an ordered set of data. The slots in the Array can store any type of data and automatically grow as data is added.

create

Can be created in a number of ways, note the following:

  • Constructor:A single numericalCreates an array of numeric length with empty array elements
    let arr1 = new Array(a);/ / an empty array
    let arr2 = new Array(5); // Create an array with numeric length for a single value
    console.log(arr2); / / / the empty x5
    Copy the code
  • Array literals: Avoid using whitespace. Methods before and after ES6 do not handle whitespace consistently
    let arr3 = [1.2.3.4];
    console.log([,,,]); // [empty x 3]
    console.log(Array.of(... [,]);// [undefined, undefined, undefined]
    console.log([,,,].join(The '-')); / / "--"
    Copy the code
  • Array.from() : Lots of features
    // String splitting
    console.log(Array.from('JayeZhu')); // ["J", "a", "y", "e", "Z", "h", "u"]
    
    // Set or map transformations (set and map later)
    const map = new Map().set(1.2).set(3.4);
    console.log(Array.from(map)); // [[1, 2], [3, 4];
    
    const set = new Set().add(1).add(2);
    console.log(Array.from(set)); / / [1, 2];
    
    / / shallow copy
    const arr1 = [1.2.3.4];
    const arr2 = Array(arr1);
    console.log(arr1 === arr2); // true
    
    // Iterators (Chapter 7, Iterators and Generators)
    const iter = { // Declare the iterator* [Symbol.iterator] () { // Generator functions that generate generator objects
        yield 1; // The yield generator stops and starts execution
        yield 2; }};console.log(Array.from(iter)); / / [1, 2];
    
    // Arguments object conversion (Chapter 10 functions, page 290)
    function getArr () {
      // Arugments is an array object of class
      return Array.from(arugments);
    }
    console.log(getArr(1.2.3.4)); // [1, 2, 3, 4];
    
    // A custom object with the necessary attributes
    const arrLikeObj = {
      0: 1.1: 2.length: 2};console.log(Array.from(arrLikeObj)); / / [1, 2];
    Copy the code
  • An Array of () : clumsy
    / / a parameter to Array, instead of an Array. The call (arugments) prototype. Slice.
    console.log(Array.of(1.2.3.4));  // [1, 2, 3, 4);
    Copy the code

access

Use brackets and indexes to access arrays

let list = [1.2.3.4];

// Normal access
console.log(list[1]); / / 2

// Out of range access returns undefined
console.log(list[4]); // undefined

// Add length, use undefined
list.length = 5;
console.log(list); // [1, 2, 3, 4, undefined]

// Reduce length and delete the corresponding index element
list,length = 3;
console.log(list); / / [1, 2, 3]
Copy the code

methods

Array method is still quite a lot, become API call engineer is the basic requirements, detailed advice to visit MDN view.

Iterator method

See chapter 7 for information on iterators

  • Keys () : returns an iterator to the array index
  • Values () : Returns an iterator for an array element
  • Entries () : Returns an iterator of index/value pairs
    let arr = ['a'.'r'.'r'];
    console.log(arr.keys()); / / [0, 1, 2]
    console.log(arr.values()); // ['a', 'r', 'r']
    console.log(arr.keys()); // [[0, 'a'], [1, 'r'], [2, 'r'],]
    Copy the code

Copy and fill methods

  • Fill () : Inserts all or part of the values into an existing array
    const arr = [1.2.3.4.5];
    arr.fill(6.2.4); // Insert the value of the first argument, the start position of the second argument, and the end position of the last argument
    console.log(arr); // [1, 2, 6, 6, 5]
    Copy the code
  • CopyWithin () : Specifies the scope of the partial contents of the shallow copy array, and then inserts it at the beginning of the specified index
    const arr = [0.1.2.3.4.5.6.7];
    arr.copyWithin(5.1.4); // The first argument refers to the location to which the copy is made, the second argument refers to the initial position of the copy element, and the third argument refers to the initial position of the copy element
    console.log(arr); // [0, 1, 2, 3, 4, 1, 2, 3]
    Copy the code

Conversion method

  • ValueOf () : Returns the array itself
  • ToString () : A comma-separated string concatenated with the equivalent strings of each value in the array
  • ToLocaleString () : calls each valuetoLocalStorage()Method that returns a comma-separated array valuestring
    const arr = [1.2.3.4.5];
    console.log(arr.valueOf()); // [1, 2, 3, 4, 5];
    console.log(arr.toString()); / / "1, 2, 3, 4, 5"
    arr[0] = {
      toLocaleString() { return "toLocaleString"; },
      toString() { return "toString"; }};console.log(arr.toLocaleString()); ToLocaleString, 2 5-tetrafluorobenzoic "/ /"
    Copy the code

The stack method

  • Push () : Adds any number of arguments to the end of the array, returning the latest length of the array
  • Pop () :deleteAn array ofThe lastOne entry, the length of the array– 1, returns the deleteditem
    const arr = [];
    console.log(arr.push(1.2)); / / 2
    console.log(arr); / / [1, 2]
    console.log(arr.pop()); / / 2
    console.log(arr); / / [1]
    Copy the code

Queue method

  • Shift () : Deletes the first item of the array and returns that item, array length -1
  • Unshift () : the arrayAt the beginningAdd as many values as you want to return an arrayThe length of the latest
    const arr = [1];
    console.log(arr.unshift(2.3)); / / 3
    console.log(arr); / / [2, 3, 1)
    console.log(arr.shift()); / / 2
    console.log(arr); / / [2, 3]
    Copy the code

Sorting method

  • Reverse () : Array elements are sorted in reverse
    const arr = [1.2.3.4.5];
    arr.reverse();
    console.log(arr); // [5, 4, 3, 2, 1]
    Copy the code
  • Sort () : defaults to each entryString()After the transformationascendingPermutations can also be passed inThe comparison functionImplementation arrangement
    const arr = [1.2.3.4.10.5];
    arr.sort();
    console.log(arr); // [1, 10, 2, 3, 4, 5]
    arr.sort((a, b) = > a - b)); // Pass in the comparison function
    console.log(arr); // [1, 2, 3, 4, 5, 10]
    Copy the code
    Therefore, numeric arrays are not suitable to use 'sort()' directly, so let's just pass the comparison functionCopy the code

Operation method

  • Concat () : Creates a copy of the current array and adds parameters to the copyAt the end ofMake up aThe new array
    const arr1 = [1.2.3];
    console.log(arr1.concat('4'[5.6]); // [1, 2, 3, "4", 5, 6]
    Copy the code

    Incoming here[5, 6]It’s even with the arraySymbol.isConcatSpreadableAbout, this item defaults to true- leveling, and is set to false to prevent leveling

    const arr2 = [5.6];
    arr2[Symbol.isConcatSpreadable] = false;
    console.log(arr1.concat('4', arr2); // [1, 2, 3, "4", [5, 6]]
    Copy the code
  • Slice () : Creates a slice containing one or more of the original arrayThe new array
    const arr3 = [1.2.3.4.5];
    console.log(arr3.slice(1.3)); / / [2, 3]
    Copy the code
  • Splice () : Delete, insert, and replace
    const arr = [1.2.3.4.5];
    // Delete, passing in the location of the first element to be deleted and the number of elements to be deleted, and returning an array of deleted elements
    console.log(arr.splice(0.2)); / / [1, 2]
    console.log(arr); / / [3, 4, 5];
    
    // Insert, passing in the starting position, 0 (without deleting elements), the element to insert, and returning an empty array
    console.log(arr.splice(0.0.1)); / / []
    console.log(arr); // [1, 3, 4, 5];
    
    // Replace, passing in the position to be replaced, the number of elements to be deleted, and any number of elements to be inserted, returns an array of replaced elements
    console.log(arr.splice(0.1.2); / / [1]
    console.log(arr); // [2, 3, 4, 5];
    Copy the code

Search and location methods

  • IndexOf () : searches from scratch, returning the indexOf the first matching element or -1
  • The lastIndexOf () : withindexOf()Split up
  • Includes () : Returns true if there are assertions conforming functions, false otherwise
  • Find () : returns the first element that matches the assertion function, otherwise undefined
  • FindIndex () : Returns the value of the find return elementThe indexor– 1
    const arr = [1.2.3.4.5.4.3.2.1];
    console.log(indexOf(1)); / / 0
    console.log(lastIndexOf(1)); / / 8
    console.log(arr.includes(5); // true
    console.log(arr.find(x= > x > 4); / / 5
    console.log(arr.findIndex(x= > x > 4); / / 4
    Copy the code

    An array is searched with an assertion function that takes three arguments: the element, the index, and the array itself, and returns a true value indicating a match

An iterative approach

The following methods take two parameters: the function passed in for each element to be run, and an optional scope object that serves as the context in which the function is run.

  • Every () : Every passed function returns true, it returns true, otherwise returns false
  • Some () : The passed function returns true if it does, and false otherwise
  • Filter () : returns the element that the first passed function returns true, undefined if not encountered
  • ForEach () : Executes the passed function without returning a value
  • Map () : Executes the incoming function and returns an array of the results of each function call
    const arr = [1.2.3.4.5];
    console.log(arr.every(x= > x > 0)); // true
    console.log(arr.some(x= > x > 5)); // false
    console.log(arr.filter(x= > x > 3)); / / 4
    const arr2 = [];
    arr.forEach(x= > arr2.push(2 * x));
    console.log(arr2); // [2, 4, 6, 8, 10]
    console.log(arr.forEach(x= > 2 * x)); // [2, 4, 6, 8, 10]
    Copy the code

Merge method

The following two methods take two parameters: a recursive function each of which will run, and an optional initial value from which to start

  • Reduce () : Iterate over all items from front to back and build a final return value
  • ReduceRight () :From the back forward.
    const arr = [1.2.3.4.5];
    console.log(arr.reduce((prev, cur, index, arr) = > prev + cur)); / / 15
    console.log(arr.reduceRight((prev, cur, index, arr) = > prev + cur)); / / 15
    Copy the code

Map

Map is a new collection type in ES6, but it uses the same key/value pair storage mode as Object. Here’s why:

  • Memory usage: Map stores 50% more key/value pairs than Object for the same memory
  • Insert performance: Map performance is better by designing a large number of insert operations
  • Delete performance: The Map delete() operation is fast and thorough, suitable for massive deletion operations
  • Key-value freedom: Whereas the Object key can only be taken from a number, string, or symbol, it can use any JS type as a key

create

Created through the Map constructor

const m = new Map([['key1'.'value1'],
  ['key2'.'value2']]);Copy the code

In addition, a map can be initialized using a custom iterator

const m = new Map([
  [Symbole.iterator]: function* () { // function plus * stands for generator, see chapter 7 192
  	yield ['key1'.'value1']; // Yield causes the generator to stop and start execution, as in Chapter 7
  	yield ['key2'.'value2']; }]);Copy the code

Basic API

  • Get () : Queries the value of the incoming key, otherwise returns undefined
  • Has (): Checks if there are any incoming keys, returning true if there are, and false otherwise
  • Set (): Adds key/value pairs
  • Delete () : deletes the key-value pairs corresponding to the incoming key
  • Clear () : Clears the map instanceallKey/value pairs
    const m = new Map([]);
    / / add
    m.set('name'.'JayeZhu')
    .set('job'.'fe')
    .set('city'.'shen zhen');
    console.log(m.size); / / 3
    / / query
    console.log(m.has('name')); // true
    console.log(m.get('name')); // "JayeZhu"
    / / delete
    m.delete('name');
    console.log(m.size); / / 2
    m.clear();
    console.log(m.size); / / 0
    Copy the code

Sequence and iteration

  • Entries (): Returns an iterator for a Map instance, which is the default iterator for a Map instance
  • Keys () : Returns the iterator of the key Map instance key
  • Values () : iterator that returns the Map instance value of the key
  • ForEach () : Iterates over key-value pairs
    const m = new Map([['key1'.'value1'],
      ['key2'.'value2']]);console.log([...m.entries]); // [['key1', 'value1'], ['key2', 'value2']] 
    console.log(m.keys()); // ['key1', 'key2']
    console.log(m.values()); // ['value1', 'value2']
    Copy the code

WeakMap

WeakMap is of the Map “brother” type, and its API is a subset of Map. “Weak” describes how the JS garbage collector treats the key in WeakMap

It can be difficult to understand, especially the explanation of weak. “Weak” means that the key of WeakMap instance is not a formal reference, but a weak reference, that is, the instance has a weak reference to the key reference object.

In computer programming, a weak reference, as opposed to a strong reference, is a reference that cannot be guaranteed that the object it refers to will not be collected by the garbage collector. An object that is referred to only by weak references is considered inaccessible (or weakly accessible) and can therefore be reclaimed at any time.

const obj = {}; // obj = null; // obj recover const wm = new WeakMap([{}, 'JayeZhu']); // Weak reference, wait for garbage collection after executionCopy the code

Let’s take a look at how this feature makes WeakMap different from Map

create

Similar to Map, constructors are used to create instances, but the key in a WeakMap instance is a weak reference and therefore can only be Object or an inherited type from Object, otherwise TypeError is raised and the entire initialization fails

const key1 = { id: 1 };
const key2 = { id: 2 };
const wm = new WeakMap([
  [key1, 'value1'],
  ['key2'.'value2']]);// TypeError: Invalid value used as WeakMap **Key**
Typeof m; // ReferenceError: m is not defined
Copy the code

Basic API

WeakMap API is a subset of Map API, where clear() has been abolished because the keys of the real case can be destroyed at any time, so it is no longer necessary to destroy all key/value pairs at once

Sequence and iteration

Because the key/value pair of a WeakMap instance can be destroyed at any time and the contents cannot be seen even if the instance can be accessed, iteration is not possible

use

Private variables

Private variables are defined in functions or blocks. See Private variables in Functions in Chapter 10 (page 316). WeakMap is wrapped with closures (referring to another function that acts on a medium variable, same as Page 309 in Chapter 10)

const User = (() = > {
  const wm = new WeakMap(a);class User { // class, see Chapter 8
    constructor (id) { Constructor, see page 250 of class
      this.isProperty = Symbol('id');
      this.setId(id);
    }
    setPrivate (property, value) {
      const privateMembers = wm.get(this) | | {}; privateMembers[property] = value; wm.set(this, privateMembers);
    }
    
    getPrivate (property) {
      return wm.get(this)[property];
    }
    setId (id) {
      this.setPrivate(this.idProperty, id);
    }
    getId (id) {
      return this.getPrivate(this.idProperty); }}returnUser; }) ();// Execute the function immediately, as described in the functions section, page 314
const user = new User(1);
console.log(user.id); // undefined
console.log(user.getId()); / / 1
user.setId(2);
console.log(user.getId()); / / 2
Copy the code

DOM node metadata

DOM, introduced earlier, is one of the three main implementations of THE Document Object Model, JS, as described in Chapter 14. Because of the nature of weak references, which do not interfere with garbage collection, they are ideal for storing associated metadata.

const wm = new WeakMap(a);const loginButton = document.querySelector('#login'); // Get the button element with id login. See Chapter 16, Dom Extension, page 445
wm.set(loginButton, { disabled: true }); 
When the metadata referenced by loginButton disappears from the DOM tree, the loginButton in WeakMap is no longer strongly referenced,
// Becomes a weak reference and is then garbage collected without the DOM node remaining in memory.
Copy the code

Set

Sets are enhanced maps that bring in aggregate data structures

create

The same constructor creates an instance, but initializes it by passing in an iterable that contains elements inserted into the schemer and the instance

const s = new Set(['value1'.'value2']);
Copy the code

Alternatively, automatic iterators can also be used

const s = new Set({
  [Symbole.iterator]: function* () {
    yield ['key1'.'value1'];
    yield ['key2'.'value2'];
  }
[
Copy the code

Basic API

Much like Map, it is deleted by has() queries, delete() and clear(), except that Set instances are added by add() and there is no get() method

const s = new Set(a); s.add(1);
console.log(s.size); / / 1
Copy the code

Sequence and iteration

Values () is the default iterator for a Set instance, keys() is an alias for values(), and entries() returns iterators whose elements are repeated occurrences of each value in the collection

const s = new Set([1.2.3]);
console.log([...s.values()]); / / [1, 2, 3].
console.log([...s.keys()]); / / [1, 2, 3].
console.log([...s.entries]); // [[1, 1], [2, 2], [3, 3]];
Copy the code

WeakSet

After understanding the above WeakMap, WeakSet is not difficult to understand. It is basically the same as WeakMap, but WeakSet is not so useful and can be used to label objects

const disabledElements = new WeakSet(a);const loginbutton= docuumment.querySelectrot('#login');
disabledElements.add(loginButton); 
// Label the node with a disable label, and the element in WeakSet is deleted from the DOM tree
// The garbage collection team will go to work
Copy the code

conclusion

Object in this chapter will shine brilliantly in the later chapters, mainly concerned with Array and THE new Map, WeakMap, Set and WeakSet of ES6, which need to be well understood and grasped. Admittedly, there are many APIS for them, and they are basically inseparable from the common words “iterator” or “generator” in the article. We’ll talk more about iterators and generators in the next chapter.

Past notes

Early morning liver finished, the article may be wrong, welcome to put forward.

  • 1- What is JS
  • 2 – HTML in JavaScript
  • 3- Language basics
  • 4- Variables, scope, and memory
  • 5- Basic reference types