The deconstruction.

1. Array deconstruction

// Base type destruct
let [a,b,c] = [1.2.3];
console.log(a,b,c); / / 1, 2, 3

// Array object destruct
let [a,b,c] = [{name: 1}, {name: 2}, {name: 3}];
console.log(a,b,c); // {name: 1},{name: 2}, {name: 3}

/ /... deconstruction
let [head,...tail] = [1.2.3.4];
console.log(head,tail);/ / 1, 2 and 4

// Nested destruct
let [a,[b],c] = [1[2.3].4];
console.log(a,b,c);/ / 1, 4-trichlorobenzene

// Destruct failed as undefined
let [a,b,c] = [1];
console.log(a,b,c);// 1, undefined ,undefined

// Destruct the default assignment
let [a=1,b=2] = [3];
console.log(a,b);/ / 3 and 2
Copy the code

2. Deconstruction of objects

// Object attribute destruct
let {f1,f2} = {f1:'test1'.f2:'test2'};
console.log(f1,f2);// test1,test2

// This is one of the differences between array deconstruction and array deconstruction
let {f1,f2} = {f1:'test'.f2:'test2'};
console.log(f1,f2);// test1,test2 

// Destruct the object name
let {f1:rename,f2} = {f1:'test1'.f2:'test2'};
console.log(rename,f2);// test1, test2

// Nested destruct
let {f1: {f11}} = {f1: {f11:'test11'.f2:'test12'}}
console.log(f11);//test11

/ / the default value
let {f1='test1'.f2:rename = 'test2'} = {f1:'current1'.f2:'current2'};
console.log(f1,rename);// current1,current2
Copy the code

3. What is the principle of deconstruction?

  • For iterators that can iterate over objects, assignment is performed using the Iterator to obtain the corresponding values sequentially.
3.1 What is Interator?
  • Interator is an interface that provides a unified access mechanism for different data deconstruction. Any data deconstruction with Interator interface can process all members of the data structure in sequence at one time through traversal operations. For of in ES6 The statement is equivalent to the Iterator, which automatically looks for the Iterator interface as it iterates through the data structure.
3.2 Functions of Interator
  • Provides a unified access interface for various data deconstructions
  • Enables data deconstruction to be processed in order
  • You can use the latest ES6 command for of to traverse
function generateIterator(array) {
    let index = 0;
    return {
        next: () = > index < array.length ? {
            value: array[index++],
            done: false}, {value: undefined.done: true}}; }const iterator = generateIterator([1.2.3]);

console.log(interator.next()); / / 1
console.log(interator.next()); / / 2
console.log(interator.next()); / / 3
console.log(interator.next()); // undefined
Copy the code
3.3 Iterable
  • An iterable is an implementation of the Iterator interface. This is a complement to ECMAScript 2015. It is not a built-in or syntax, but only a protocol.

  • Iterable protocol: The object must implement the Iterator method. That is, the object or its prototype chain must have a property called symbol. Iterator. The value of this property is a no-parameter function that returns the Iterator protocol.

  • Iterator protocol: Defines the standard way to produce a finite or infinite sequence of values, which requires that a next() method be implemented that returns the object done(Boolean) and value attributes.

3.4 Implement a for of traversal object
  • A custom data deconstruction can become an iterable that can be iterated over by a for of loop, as long as you have an Iterator interface and deploy it to your Symbol. Iterator property.
const obj = {
    count: 0[Symbol.iterator]: () = {
        return {
            next: () = > {
                obj++;
                if(obj.count <= 10) {
                    return {
                        value: obj.count,
                        done: false}}else {
                    return {
                        value: undefined.done: true}}}}}};for (const item of obj) {
    console.log(item);
}


/ / or
const iterable = {
    0:'a'.1:'b'.2:'c'.length: 3[Symbol.iterator]:Array.prototype[Symbol.iterator]

};

for (const item of iterable) {
    console.log(item);
}
Copy the code

2. Traversal

1. Array traversal

1.1 for, forEach, for of
const list = [1.2.3.4.5.6.7.8];

// for
for (let i = 0; len = list.length; i< len; i++) {
    if(list[i] === 5) {
        break; / / 1, 2, 3, 4
        // continue; / / 1,2,3,4,6,7,8
    }
    console.log(list[i]);
}

// forEach
const list = [1.2.3.4.5.6.7.8];
list.forEach((item,index,arr) = > {
    if (item === 5) return;
    console.log(index); // 0 1 2 3 4 6 7 8
    console.log(item); // 1 2 3 4 6 7 8
});

for (const item of list) {
    if (item === 5) {
        break; // 1, 2, 3, 4
        // continue; // 1 2 3 4 6 7 8}}Copy the code
  • Conclusion:
  1. All three traverse the array from left to right

  2. ForEach cannot break out of loops, and for and for of can use break or continue interrupts

  3. For traverses a set of indexes. The forEach callback has richer parameters. Elements, indexes, and arrays can be retrieved directly

  4. For of and for are also executed if there are empty elements in the array

1.2 the filter and the map
//filter
const list = [
{id: 1.name: 'a little'.age: 11}, {id: 2.name: 'small 2'.age: 12},
{id: 3.name: 'small three'.age: 13}];const reslist = list.filter(item= > item.age === 11);
console.log(reslist); // {id: 1, id: 1, age: 11}

// map 
const newlist = list.map(item= > item.id);
console.log(newlist); / / [1, 2, 3]

Copy the code
  • Conclusion:
  1. Both generate a new array, without changing the original array

  2. Both will skip the empty element

  3. Map assembles the return values of the callback function into a new array of the same length as the original array

  4. Filter combines the elements of the callback function condition into a new array of different lengths

  5. The new array elements generated by map can be customized

6. The array elements generated by filter cannot be customized and are the same as the original array elements

1.3 some 、every
// some
const list = [1.2.3.4.5.6];
const newlist = list.some(item= > item > 5);
console.log(newlist); // true

const everyList = list.every(item= > item > 5);
console.log(newlist); // false
Copy the code

Conclusion:

  • Both are used to do array judgment, both return a Boolean value,
  • Some: Returns true if one element in the array meets the criteria, the loop breaks, and false is returned if all elements do not meet the criteria
  • Every: The opposite of some, returns false if one element in the array does not meet the criteria, and the loop is broken if all elements meet the criteria, returns true;
1.4 the find, findIndex
const list = [
{id: 1.name: 'a little'.age: 11},
{id: 2.name: 'small 2'.age: 12},
{id: 3.name: 'small three'.age: 13}];const result = list.find(item= > item.id === 3);
console.log(result);// {id: 3, name: '小三', age: 13}

const index = list.findIndex(item= > item.id === 3);
console.log(index); / / 2
Copy the code

Conclusion:

  • The find method returns the value of the first element in the array that satisfies the callback function, or undefined if none exists
  • The find method returns the index of the element searched in the array, or -1 if none exists;
  • Both are used to find array elements
1.5 the reduce and reduceRight
  • The reduce method takes two arguments, the first being a callback and the second an initialValue.
// Calculates the sum of an attribute in an array of objects
const list = [
{id: 1.name: 'a little'.age: 11},
{id: 2.name: 'small 2'.age: 12},
{id: 3.name: 'small three'.age: 13}];const sum = list.reduce((a, item) = > {
    return a + item.id;
},0);
console.log(sum); / / 6
Copy the code
  • ReduceRight method also receives 2 parameters, the first parameter is the callback function (callback), the second parameter is the initialValue (value);

array.reduceRight(function(total, currentValue, currentIndex, arr), initialValue)

  1. Total Initial value, the value returned after calculation
  2. CurrentValue Indicates the current element
  3. CurrendIndex Index of the current element
  4. Arr The array object to which the current element belongs
// Evaluates the sum of the elements in the array
let arr = [0.1.2.3.4];
const result = arr.reduceRight((total,item,index,arr) = > {
    return total + item;
},0);
console.log(result); / / 10
Copy the code

2. Object traversal

2.1 for the in
  • When iterating over a number array, the key is the array subscript string, the object is iterated over, and the key is the object field name
let obj = {a: 'test1'.b: 'test2'};
for (let key in obj) {
    console.log(key,obj(key)); 
    //a test1
    // b test2
}
Copy the code

Disadvantages: 1. For in not only iterates through the current object, but also includes enumerable properties on the prototype chain. 2

2.2 Object. Keys
  • The change method returns an array of the given object’s own enumerable properties
const obj = {a:1.b:2};
const keys = Object.keys(obj);// [a,b]

// Manually simulate the implementation of Object.keys

function getObjectKeys(obj) {
    const result = [];
    for (const prop in obj) {
        if(obj.hasOwnProperty(prop)) { result.push(prop); }}return result;

}
Copy the code
2.3 the Object values
  • This method returns an array of all enumerable property values for a given object itself
const obj = {a:1.b:2};
const keys = Object.values(obj);/ / [1, 2]

// Manually simulate the object. values implementation

function getObjectValues(obj) {
    const result = [];
    for (const prop in obj) {
        if(obj.hasOwnProperty(prop)) { result.push(obj[prop]); }}return result;

}
Copy the code
2.4 Object. Entries
  • This method returns an array of key-value pairs of the given object’s own enumerable properties
const obj = {a:1.b:2};
const keys = Object.entries(obj);/ / [[' a ', 1], [' b ', 2]]

// Manually simulate the object. values implementation

function getObjectEntries(obj) {
    const result = [];
    for (const prop in obj) {
        if(obj.hasOwnProperty(prop)) { result.push(prop,obj[prop]); }}return result;

}
Copy the code
2.5 Object. GetOwnPropertyNames
  • This method returns an array of enumerable or non-enumerable property names that obJ owns.
Object.prototype.aa = '1111';
const testData = {a: 1.b: 2 }
for (const key in testData) {
    console.log(key);
}
     console.log(Object.getOwnPropertyNames(testData));
//a
// b
// aa
// [ 'a', 'b' ]
Copy the code