javascript advanced programming collection type reference

Keywords: Javascript node.js Vue.js

#javascript advanced programming (VI) collection type reference

1, Object

  1. How to explicitly create an object instance
    (1) new + constructor

    let person = new People();
    person.name = "abc";
    person.age = 27;
    

    (2) Object literal

    let person = {
    	name: 'abc',
    	age: 28
    }
    

    tips:
    a. Numeric property names are automatically converted to strings
    b. When using the object literal method, the object constructor is not called

2, Array

  1. Create array
    (1) Array constructor

    let colors = new Array(5) // Create an array with a length of 5. new can be omitted
    let names = new Array('Greg') // Create an array with length 1 and element Greg
    

    (2) Array literal

    let colors = ['red', 'blue', 'yellow']
    

    Similarly, Array literals do not call the Array constructor when creating an Array.

    (3) from() and of() [provided by ES6]
    from(): convert class array structure to array

    // Splitting strings into arrays
    console.log(Array(['matt']) // ['m', 'a', 'a', 't']
    
    // Collection and map types can be converted into arrays
    const m = new Map().set[1,2]
    					.set[3,4]
    console.log(Array.from(m)) // [[1,2],[3,4]]
    
    // The Array.from() method also accepts the second parameter, which is a mapping function. Each element is mapped accordingly
    const a = [1,2,3,4];
    const b = Array.from(a, x=>x**2);
    console.log(b) // [1,4,9,16]
    

    of(): used to replace the method used before ES6 to convert arguments object into array: Array.prototype.slice.call(arguments)

  2. Detection array
    When there is only one web page (i.e. only one global execution context):

    a instanceof Array
    

    When there are multiple web pages, there may be multiple frames, resulting in multiple constructors in Array:

    Array.isArray(a)
    
  3. iterator
    Contains three iterators:
    keys(): index iterator
    values(): array element iterator
    entries(): Index / value iterator

    const a = ['a', 'b', 'c', 'd'];
    console.log(Array.from(a.keys())); // [1,2,3,4]
    console.log(Array.from(a.values())); // ['a', 'b', 'c', 'd']
    console.log(Array.from(a.entries())); // [ [ 0, 'a' ], [ 1, 'b' ], [ 2, 'c' ], [ 3, 'd' ] ]
    
  4. Filling method

    fill()

    let a = [0,0,0,0,0]
    // fill(value,start,end)
    console.log(a.fill(6, 3, 4)) // [ 0, 0, 0, 6, 0 ]
    
  5. Conversion method

let a = [0,0,0,0,0];
console.log(a.valueOf()); // [0, 0, 0, 0, 0] (original array)
console.log(a.toString()); // 0,0,0,0 (a comma separated string)
// join() sets the delimiter of the toString method
console.log(a.join('\\')); // 0\0\0\0\0
  1. Stack, queue method
    push(),pop(),shift(),unshift()

  2. Sorting method
    reverse(): reverse
    sort():

// Ascending order: left right
console.log(a.sort((val1, val2) => (val1-val2))) // [ 0, 1, 2, 3, 4 ]
// Descending order: right left
console.log(a.sort((val1, val2) => (val2-val1))) // [ 4, 3, 2, 1, 0 ]
  1. Array flattening
    concat()
let colors = ['red', 'blue', 'yellow']
console.log(colors.concat(['black'], 'green')); // [ 'red', 'blue', 'yellow', 'black', 'green' ]
// Set symbol.isconcapspreable to prevent concat from flattening the array and simply connecting.
colors[Symbol.isConcatSpreadable] = false;
console.log(colors.concat(['black', 'pink'], 'green'));
// output
[
  [
    'red',
    'blue',
    'yellow',
    [Symbol(Symbol.isConcatSpreadable)]: false
  ],
  'black',
  'pink',
  'green'
]
  1. slice(start, end): create an array (array slice) containing some elements of the original array
    The two indexes are left closed and right open
let colors = ['red', 'blue', 'yellow']
console.log(colors.slice(1,2)); // ['blue']
  1. splice(start, length, content1, content2,...)
    (1) Delete some continuous elements: the content is empty and the length is customized

    let colors = ['red', 'blue', 'yellow']
    colors = colors.concat(['black', 'pink'], 'green')
    // concat flattened array
    console.log(colors); // [ 'red', 'blue', 'yellow', 'black', 'pink', 'green' ]
    
    let t = colors.splice(2, 2)
    // The splice function returns the deleted element
    console.log(t); // [ 'yellow', 'black' ]
    // And modify the original array
    console.log(colors); // [ 'red', 'blue', 'pink', 'green' ]
    

    (2) Replace some continuous elements: the number of content is consistent with the length

    let t = colors.splice(1,3, 'dark', 'gray', 'purple')
    // Returns the replaced value
    console.log(t); // [ 'blue', 'yellow', 'black' ]
    // Update original array
    console.log(colors); // [ 'red', 'dark', 'gray', 'purple', 'pink', 'green' ]
    

    (3) Insert some elements: length is 0

    let t = colors.splice(2, 0, 'dark', 'gray', 'purple')
    console.log(t); // []
    console.log(colors); // ['red', 'blue', 'dark',   'gray','purple', 'yellow', 'black',  'pink',  'green']
    
    
  2. lookup
    (1) Strictly equal (same value, same type)
    indexOf(element, [start]): search for element from left to right from start, and return the index value of element. If there is no element, return - 1.
    lastIndexOf(element, [start]): the same as above, and the search direction is from right to left.
    includes(element, [start]): a new method in ES6, which returns true, but not false
    (2) By assertion function
    find(element, index, array): element can restrict the elements screened. Index is the index of the element to be searched and returns the first matching element
    findIndex(element, index, array): returns the first matching index

    const people = [
        {
            name: 'Matt',
            age: 27
        },
        {
            name: 'Jack',
            age: 30
        },
        {
            name: 'Tom',
            age: 25
        },
    ]
    console.log(people.find((el, index, array) =>el.age< 30)) // { name: 'Matt', age: 27 }
    
  3. Iterative method

    every(function): if each item runs, the function returns true, and returns true

    some(function): returns true if a running function returns true

    filter(function): filter out items that meet the operation of the function

    For each (function): each item is processed in a functional manner, with no return value

    map(function): process each item in a functional way and return an array of processing results.

    console.log(people.every((p)=>p.age < 31)); // true
    console.log(people.some((p)=>p.name === 'Matt')); // true
    console.log(people.filter((p)=>{return p.age < 29})); // [ { name: 'Matt', age: 27 }, { name: 'Tom', age: 25 } ]
    
    people.forEach((p)=>{p.age ++}) 
    console.log(people); 
    // output
    [
      { name: 'Matt', age: 28 },
      { name: 'Jack', age: 31 },
      { name: 'Tom', age: 26 }
    ]
    
    console.log(people.map((p)=>{p.age++; return p}));
    // output
    [
      { name: 'Matt', age: 29 },
      { name: 'Jack', age: 32 },
      { name: 'Tom', age: 27 }
    ]
    
    
  4. Merging method

    reduce(function(pre, cur, [index, array]),[startVal]): starting from the index value (0,1), each pair of elements needs to set the return value.

    The initial value can be set, and the initial wheel changes to function (initial value, arr[0])

const people = [
    {
        name: 'Matt',
        age: 27
    },
    {
        name: 'Jack',
        age: 30
    },
    {
        name: 'Tom',
        age: 25
    },
]
console.log(people.reduce((prev, cur, index, arr)=>
{
    console.log(prev.age, cur.age);
    return {name: 'xxx',
            age: prev.age+cur.age,
    }}
)) // { name: 'xxx', age: 82 }

3, Map

const p = new Map();
p.set('1001', 'Ann');
p.set('1002', 'Bob')
console.log(p); // Map(2) { '1001' => 'Ann', '1002' => 'Bob' }
console.log(p.has('1001')); // true
console.log(p.get('1001')); // Ann

Map will maintain the inserted key values in order, that is, the map structure is orderly.

Iterators are the same as arrays:
keys(): index iterator
values(): array element iterator
entries(): Index / value iterator

The difference between map and object

  1. The key of map does not limit the type, and the object limits that it can only be string values and symbols
  2. The elements of map are in order, and the attributes of object have no order
  3. map inherits object
  4. map supports iteration, but object does not

Posted by lucie on Tue, 21 Sep 2021 02:34:07 -0700