Note:!!

Promise is summarized in another article: Promise starts with Customization

1. Let the keyword

1. Function: Similar to var, used to declare a variable

2. Features:

  • Valid in block scope

  • Cannot duplicate declaration

  • There is no variable promotion, that is, variables can no longer be used before initialization. Be sure to declare before use.

  • Globally-declared variables are not mounted to the window, but are placed on script variable objects (temporary dead range).

  • The scope chain is not affected

3. Application:

  • Loop through to add listeners

Example:

//对比var
console.log(a); // undefined
var a = 123;
var a = 234;
console.log(a);

// The declaration cannot be repeated
let star = 'Lo Zhixiang';
let star = 'pig';

// There is no variable promotion
// console.log(b); //b is not defined
console.log(ausername);  //Cannot access 'ausername' before initialization
let ausername = 'wade';

// valid in block scope
//if else while for 
{
    let girl = 'Zhou Yangqing';
}
console.log(girl);


// apply - valid in block scope - loop through to add listener
//let fixes the problem where "I =3" is always displayed when a button is clicked and "the NTH button is clicked"
let btns = document.getElementsByTagName('button');
for (let i = 0; i < btns.length; i++) {
    var btn = btns[i];
    btn.onclick = function () { alert(i); }}Copy the code

2. The const keyword

1. Function: Define a constant

2. Features:

  • Do not modify

  • A value must be assigned when declared

  • Identifiers are generally capitalized (unspoken rule)

  • Valid in block scope

  • Cannot duplicate declaration

  • There is no variable promotion

3. Application: Generally declare the object type to use const, non-object type to choose let

4. Note that object property changes and array element changes do not trigger const errors, because the address to which the object refers is the same!

Example:

Example:// Declare constants
const SCHOOL = Silicon Valley;
// The initial value must be assigned
const A; / / an error
// Use uppercase for general constants (unspoken rule)
const A = 100;
// The value of a constant cannot be modified
SCHOOL = 'ATGUIGU';
console.log(SCHOOL);
// Array and object element changes are not counted as constant changes, the object name points to the same address.
const TEAM = ['UZI'.'MXLG'.'Ming'.'Letme'];
TEAM.push('Meiko');
Copy the code

3. Destructively assigning variables (emphasis!)

1. To understand:

  • Extract data from objects or arrays and assign values to variables (multiple)

2. Object deconstruction assignment

let {n, a} = {n:’tom’, a:12};

  • Request value by key (request on demand)

3. Array deconstruction assignment

let [a,b] = [1, ‘atguigu’];

  • Obtain a value based on index

4. The application

  • The argument passed in is an object that is deconstructed using the function’s parameters

Example:

// Object destruct assignment
let obj2 = {username:'kobe'.age: 43};
let {username, age} = obj2;  // What we really need to do is get value by key.
console.log(username, age);

// Array destruct assignment
let arr = [4.5.3];
let num1 = arr[2];
let num2 = arr[1];
console.log(num1, num2);

let [a,b] = arr;  // Retrieve value from index
let [,,c] = arr;  // use placeholder to take the following value
console.log(a,b); / / 4 5
console.log(c);  / / 3


// apply - Use the function's parameters to deconstruct the arguments
function fun({username, age}) {
    // let argument = argument;
    // let {username, age} = {username:'kobe', age: 43};
    console.log(username);
    console.log(age);
}
fun(obj2);
Copy the code

4. Template string

1. Understanding: Simplified string concatenation

  • Template strings must be included with ‘ ‘

  • The portion of the variable is defined with ${XXX}

Example:

let obj = {username: 'kobe'.age: 43};
let str = 'My name is:' + obj.username + ', my age is: + obj.age;
console.log(str);
let str1 = 'My name is:${obj.username}My age is:${obj.age}`;
console.log(str1);
Copy the code

5. Simplified writing of objects

1. Omit the attribute value with the same name

2. Omit functions and colons:

Example:

//ES5
let obj = {
    username: username,
    age: age,
    showName: function () {
        console.log(this.username); }};console.log(obj);
obj.showName();

//ES6
let obj = {
    username,  // Attributes with the same name can be omitted --> key and value are the same
    age,
    showName() {  // omit the function and colon
        console.log(this.username); }};console.log(obj);
obj.showName();
Copy the code

6. Arrow function (emphasis!)

Let fun = parameter => function body

2. Parameter:

  • No arguments: () => function body

  • One argument – parentheses can be omitted: I => function body

  • Greater than one argument: (I,j) => function body

3. Key points: function body

  • When there is only one statement or expression: {} can be omitted

  • When there are multiple statements: {} cannot be omitted

  • When {} is omitted, it automatically returns the result of the current statement or expression

  • If there is only one statement and return object, omitting the parentheses {} can cause problems, so we need to enclose the object with parentheses:

    const fn = b => ({a:’22’, c: b})

Characteristics of 4.

  • Arrow functions do not have their own this, not when called, but when defined

  • Expand understanding:

    • The arrow function is defined to see if there are any non-arrow functions on the outside. If so, this of the current arrow function points to the same object as this of the outer function

    • If not, this points to the window

  • Arrow functions cannot be used as constructors

  • Can’t use arguments

Example:

// When arrow functions have no parameters, () cannot be omitted
let fun = () = > console.log('fun()');
fun();

// When the arrow function has only one parameter, () may or may not be omitted
let fun1 = a= > console.log('When there is only one parameter', a);
fun1(123);

// When arrow functions have multiple parameters, () cannot be omitted
let fun2 = (a, b) = > console.log('When there are more than one parameter', a, b);
fun2(1.2);

If {} is omitted, it automatically returns the result of the current statement or expression. If {} is not omitted, you need to manually specify the return result. Otherwise, return value: undefined is executed by default.
let fun3 = () = > console.log('When the function body has only one statement'); // The result of the statement
console.log(fun3());
// let fun3 = () => 123
// console.log(fun3());

If {} is not omitted, you need to manually specify the return result. Otherwise, return value: undefined is executed by default.
let fun4 = () = > {
    let a = 1;
    console.log('Function body has multiple statements', a);
    // return a;
}
console.log(fun4());

// The arrow function this points to the problem
btn1.onclick = function () {
    console.log(this); / / btn1 object
};

btn2.onclick = () = > console.log(this); // window

let obj = {
    username: 'kobe'.test: function () { // this ---> obj
        btn2.onclick = () = > console.log(this); // obj}}let obj = {
    username: 'kobe'.test:  () = > {
        btn2.onclick = () = > console.log(this); // window}}; obj.test();// Arrow functions cannot be used as constructors
let Person = () = > this.name = 'kobe';
let person1 = new Person();

// Arguments cannot be used
let fn = () = > {
    console.log(arguments);
}
fn(1.2.3);



/ / case
Requirement 1: click div 2s and the color becomes "pink"
// Get the element
let ad = document.getElementById('ad');
// Bind events
ad.addEventListener("click".function(){
    // let _this = this; / / this cache
    / / timer
    // setTimeout(function () {
    // // Change the background color this
    // console.log(this);
    // _this.style.background = 'pink';
    // }, 2000);
    
    setTimeout(() = > {
        this.style.background = 'pink';
    }, 2000);
});


Requirement 2: Return an even number of elements from an array
const arr = [1.6.9.10.100.25];
// const result = arr.filter(function(item){
// if(item % 2 === 0){
// return true;
// }else{
// return false;
/ /}
// });

const result = arr.filter(item= > item % 2= = =0);
console.log(result);
Copy the code

Conclusion:

  • The arrow function is suitable for callbacks unrelated to this. For example: timer, array method callback!

  • Arrow functions are not suitable for callbacks related to this. For example: event callbacks, object methods!

7. Three-point operators – REST (variable) arguments/extended operators (unpack)

1. The variable name

2. Application:

1) REST (variable) parameters

  • Used to get arguments to a function

  • Is used instead of arguments and is more flexible than arguments

  • The argument collection using the three-point operator is a true array

  • You have to put it at the end of the argument

2) Extend operators (unpack)

  • Gets each item in an array

  • How it works: The three-point operator calls the iterator interface, which, if there is an underlying interface, iterates through the array

  • Application: Convert a pseudo-array to a true array

Example:

//rest(variable) arguments
function fun(a,b, ... values) {
    // arguments pseudo-arrays used to collect arguments
    // Pseudo-array: has the length attribute, can get the corresponding value by subscript, but does not have the general method of array (push, filter, map)
    console.log(arguments);
    console.log(a);
    console.log(values);
    values.forEach(function (item, index) {
        console.log(item, index);
    });
}
fun(2.3.4.5);


// Extend operator (unpack)
let arr2 = [2.3.4.5];
let arr3 = [1. arr2,6];
console.log(arr3);  // [1, 2, 3, 4, 5, 6]
/ /... Operator to unpack the specified array
console.log(... arr2);// Array clone - deep copy
console.log([...arr2]);

/ /... Operators to unpack cannot traverse an object directly
let obj2 = {name: 'kobe'.age: 43};
// console.log(... obj2); / / an error

/ /... The operation matches the merge object/copy object
let obj3 = {sex: 'male'. obj2};// We can construct literal objects using... The operator
letobj4 = {... obj2};console.log(obj3);
console.log(obj4);

// Merge while changing or adding value
let person = {name:'tom'.age:18}
letperson3 = {... person,name:'jack'.address:"The earth"}
console.log(person3);

// Convert the pseudo-array to a real array
const divs = document.querySelectorAll('div');
const divArr = [...divs];
console.log(divArr);
Copy the code

8. Parameter default values

1. Initial parameter value

  • Parameters with default values, usually placed later (unspoken rule)

Application 2.

  • Combine with deconstruction assignment!

Example:

function Point(x = 0, y = 0) {
    // Native implementation
    // if(! x && x ! = = 0) {
    // x = 0;
    // }
    // if(! y && y ! = = 0) {
    // y = 0;
    // }
    
    this.x = x;
    this.y = y;
}
let point = new Point(22.45);
console.log(point);

let point2 = new Point();
console.log(point2);


// The type of the parameter default usually depends on the type of argument needed
function fun(arr = []) {
    arr.forEach(function (item, index) {
        console.log(item, index); })}let arr = [1.2.3];
fun(arr);
fun();


// Apply - combine with destruct assignment!!
function connect({host="127.0.0.1", username, password, port}){
    console.log(host)
    console.log(username)
    console.log(password)
    console.log(port)
}
connect({
    host: 'atguigu.com'.username: 'root'.password: 'root'.port: 3306
})
connect({
    username: 'root'.password: 'root'.port: 3306
})
Copy the code

9.Symbol

1. Understand: ES6 provides a new primitive (basic) data type symbol

Review:

  • Basic data types: String, Number, Boolean, null, undefined, Symbol

  • Typeof return values: string, number, Boolean, object, undefined, symbol, function

Characteristics of 2.

  • The value of the Symbol attribute is unique, resolving naming conflicts

  • The Symbol value cannot be evaluated with other data, including the same string

  • The symbol attribute is not traversed for in

3. Built-in Symbol value

  • Symbol.iterator

    • Object’s symbol. iterator property, pointing to the default iterator method for that object

Example:

/ / use the symbol
let symbol = Symbol(a);let symbol2 = Symbol(a);console.log(symbol);
console.log(symbol2);
// Verify that the value is unique
console.log(symbol === symbol2);
console.log(typeof symbol);

//Symbol function passes the parameter
let symbol3 = Symbol('one');
let symbol4 = Symbol('two');
console.log(symbol3);
console.log(symbol4);
// Verify that the value is unique
console.log(symbol3 === symbol4);

// Use symbol as the attribute name of the object
let symbol5 = Symbol(a);let obj = {};
obj[symbol5] = 'hello';
console.log(obj);

// Built-in Symbol value: symbol.iterator
console.log(Symbol.iterator);
Copy the code

10.for… Of and iterator interface implementation (difficult!)

1. For (let value of target){

1) Go through the number group

2) Iterate through Set

3) Traverse the Map

4) Iterate over the string

5) Iterate over the pseudo-array

2. The iterator interface

  1. concept
  • Iterator is an interface mechanism that provides unified access to various data structures.
  1. role
  • Provide a unified and easy access interface for various data structures.

  • Allows the members of a data structure to be arranged in some order.

  • ES6 created a new traversal command for… The of loop is an iterator interface for… Of calls.

  1. The working principle of
  • Create a pointer object (traverser object/iterator object) that points to the start of the data structure.

  • The first time the next method is called, the pointer automatically points to the first member of the data structure

  • The next method is called over and over again, and the pointer moves backwards until it points to the last member

  • Each call to next returns an object containing value and done, {value: the value of the current member,done: a Boolean}.

    • Value indicates the value of the current member, and the Boolean value corresponding to done indicates whether the structure of the current data has been traversed.

    • When the traversal ends, the value returned is undefined, and the done value is true

  1. Data structures with native Iterator interfaces (available for… Of traversal)

1) Array

2) the arguments

3

4) Map container

​ 5)String ​ …

Note:… Operators also call the iterator interface to implement traversal!

Example:

let arr = [1.2.3.4.5.1.2.3.4];
let set = new Set(arr);
/ / traverse the set
for(let item of set){
    console.log(item);
}
console.log(... set);// Iterate over the string
let str = 'abcd'
for(let item of str){
    console.log(item);
}

// Iterate over the pseudo-array
let btns = document.getElementsByTagName('button');
for(let item of btns){
    console.log(item);
}

/ / verification for... Of the... The operator calls the iterator interface
let arr = [2.3.4.5];
// Array.prototype[Symbol.iterator] = 1111;
console.log(arr);
for(let item of arr){
    console.log(item);
}
console.log(... arr);// A simple implementation of the underlying iterator interface (method/API) - manually call next() to move the pointer
function iteratorUtil(target) {
    let index = 0; // Identifies the starting position of the pointer
    return { // Generate an iterator object
        next: function () {
            returnindex < target.length? {value: target[index++], done: false}, {value: target[index++], done: true}}}}let iteratorObj = iteratorUtil(arr);  // Generate an iterator object
console.log(iteratorObj.next());
console.log(iteratorObj.next());
console.log(iteratorObj.next());
console.log(iteratorObj.next());
console.log(iteratorObj.next());
console.log(iteratorObj.next());


// A complete implementation of the underlying iterator interface (method/API) - iterable arrays/strings/objects
function iteratorUtil() {
    //console.log(' my method was called ', this); // This is the target array/string/object to iterate over
    // console.log(target); // undefined, so the target parameter can be removed
    let that = this;  / / this cache
    let index = 0;  // Identifies the starting position of the pointer
    let keys = Object.keys(that);  // Get an array of all keys in the object
    if(this instanceof Array || this instanceof String) {// Iterate over the number group/string
        return {  // Generate an iterator object
            next:  function (){  // We can use the arrow function to solve the pointing problem of this
                returnindex < that.length? {value: that[index++], done: false}, {value: that[index++], done: true}; }}}else {  // Iterate over the object
        return {  // Generate an iterator object
            next:  function (){  // We can use the arrow function to solve the pointing problem of this
                returnindex < keys.length? {value: that[keys[index++]], done: false}, {value: that[keys[index++]], done: true}; }}}}// Use your own iterator interface to implement for... of/... Operator traversal
Array.prototype[Symbol.iterator] = iteratorUtil;
Object.prototype[Symbol.iterator] = iteratorUtil;

// go through the number group
let arr = [2.3.4.5];
// for of calls the iterator interface
// The three-point operator calls the iterator interface
for(let item of arr){
    console.log(item);
}
console.log(... arr);// Iterate over the object
let obj = {
    username: 'kobe'.age: 43
};
// console.log(Object.keys(obj)); // Get an array of all keys in the object
for(let o of obj){
    console.log(o);
}

// Iterate over the string
let str = "abcdef";
for(let s of str){
    console.log(s);
}
console.log(... str);Copy the code

11.Class (important!)

1. Define a class by class

2. Define a constructor in a class by constructor

3. Use new to create an instance of the class

4. Class inheritance through extends – equivalent to ES5 archetypal inheritance

5. Call the parent class’s constructor through super – equivalent to ES5’s constructor inheritance

6. Use the static resource modifier to add attributes to the class object itself

7. Override generic methods inherited from parent classes – the arguments and method names must be the same

Note:

  1. Extends does: 1. The prototype of a subclass becomes instance 2 of its parent class. Add the constructor attribute and point to the subclass itself

  2. Super does: 1. Calls the parent constructor. 2. Changes the parent constructor’s this to an instance of a subclass

  3. Super must be written first in subclass constructor (all this). Preceding the operation)

  4. A constructor in a class is not required to be written; it is only written when an instance is initialized, such as when a specified attribute is added.

  5. If class A inherits from class B, and class A writes constructors, then super in class A constructors must be called.

  6. The methods defined in the class are placed on the prototype object of the class for instance to use.

  7. Methods in the class have strict mode turned on by default

Example:

// Define a human: Person
class Person {
    // Static resource modifier. Use static to add attributes to the class object itself
    static num = 123;
    Add an attribute to the Car instance called wheel with the value 4.
    // assign the constructor value: this.wheel = 4;
    wheel = 4;

    // Class constructor
    constructor(name, age){
        // Who is this in the constructor? Class instance object
        console.log('--- constructor() ---');
        this.name = name;
        this.age = age;
        //this.wheel = 4;
    }
    // The general method of class
    // Where is the showInfo method? Class on a prototype object for instance use
    // When showInfo is called from a Person instance, this in showInfo is the Person instance
    showInfo(){ // userInfo
        console.log(this.name, this.age); }}// The Person class adds its own attributes
Person.msg = 'Attributes of Person itself';
console.log(Person.msg);
console.log(Person.num);

// Use classes in the same way as constructors
let person1 = new Person('kobe'.43);
console.log(person1);
person1.showInfo();

// Define a subclass
class Child extends Person {  // Extends does: 1. The prototype of a subclass becomes instance 2 of its parent class. Add the constructor attribute and point to the subclass itself
    constructor(name, age, sex) {
        Call the parent constructor. Change the parent constructor's this to an instance of a subclass
        super(name, age);  // super calls the constructor of the parent class
        this.sex = sex;
    }
    // Superclass method rewriting: when the method of the superclass prototype does not meet the needs of the subclass instance
    // Where is the showInfo method? Class on a prototype object for instance use
    When showInfo is called from a Child instance, this in showInfo is the Child instance
    showInfo(){
        console.log(this.name, this.age, this.sex); }}let child1 = new Child('xiaoming'.18.'male');
console.log(child1);
child1.showInfo();
Copy the code

12. Method extension for Number

1. Number.isfinite () : check whether the Number is of finite size

2. Number.isnan () : check whether it is a NaN

3.Number.isInteger() : checks whether it is an integer

4. Number.parseint () : Converts a string to a numeric value

Note: window.parseInt has the same function as number. parseInt

Example:

console.log(Number.isFinite(123)); // true
console.log(Number.isFinite(NaN)); // false
console.log(Number.isFinite(Infinity)); // false
console.log(Number.isNaN(NaN)); //true
console.log(Number.isInteger(22)); //true
console.log(Number.parseInt('123abc')); / / 123

/ / pen test
let str1 = '23.23';
let str2 = '34.34';
console.log(parseInt(str1) + parseInt(str2)); / / 57
console.log(parseInt(str1 + str2)); / / 23
Copy the code

13. Object method extension

1.Object.is(v1, v2)

  • Determine whether two pieces of data are exactly the same

2.Object.assign(target, source1, source2..) (Important!)

  • If you copy the properties of one or more source objects to the target object, the values of the same property name of the target object are overwritten. This method modifies the target object.

3. Direct manipulation of the __ proto __ attribute (ES6)

let obj2 = {};
obj2.__proto__ = obj1;
Copy the code

Example:

// Special value comparison
console.log(0= = = -0); // true
console.log(NaN= = =NaN); // false

// object. is(v1, v2) see if the two values are exactly the same
console.log(Object.is(0, -0)); // false
console.log(Object.is(NaN.NaN)); // true

//Object.assign(target, source1, source2..)
let target = {}; // target
let sources1  = {name: 'kobe'};
let sources2 = {age: 43};
// Clone/copy
let result = Object.assign(target, sources1, sources2);
console.log(result);
console.log(target);

// Operate directly on the __proto__ attribute
let obj3 = {};
obj3.__proto__ = target;
console.log(obj3);
Copy the code

14. The Set and Map

1.Set

  1. ES6 provides a new data structure called a Set, an unordered collection of non-repeatable values.

  2. Set properties and methods:

1- Set()/Set(array) constructor

2-size Returns the number of elements in the collection

3-add () adds a new element and returns the current collection

4-delete () deletes the element, returning Boolean

5-has () checks whether the collection contains an element, returning Boolean

6-clear () clears the collection and returns undefined

  1. Set implements the Iterator interface, so you can use extended operators… And for… Of traverses

Example:

/ / declare the set
let s = new Set(a);console.log(s, typeof s);
// Pass the array declaration set
let s2 = new Set(['The Big thing'.'Little things'.'Good thing'.'Bad thing'.'Little things']);
// Number of elements
console.log(s2.size);
// Add a new element
s2.add('Happy event');
// Delete elements
s2.delete('Bad thing');
/ / testing
console.log(s2.has('Dregs'));
/ / to empty
s2.clear();
console.log(s2);

/ / in the ES6 for... Instead of for... And in the forEach ()
for(let v of s2){
    console.log(v);
}
Copy the code

2.Map

  1. ES6 provides Map data structures. It is similar to an object, but also a collection of key-value pairs.

However, the scope of “keys” is not limited to strings; all types of values (including objects) can be used as keys.

  1. Map also implements the Iterator interface, so you can use extension operators… And for… Of traverses

  2. Map attributes and methods:

1) Map()/Map(two-dimensional array) constructor

2) size Returns the number of Map elements

3) Set (key, value) adds a new element to return the current Map

4) Get () returns the key value of the keyname object

5) has() checks if the Map contains an element, returning Boolean

​ 6) clear() 清空集合,返回 undefined

Example:

/ / declare the Map
let m = new Map(a);// Pass in a two-dimensional array to declare Map
let map = new Map([[1.'abc'], ['age'.123]]);
console.log(map);
// Add elements
m.set('name'.Silicon Valley);
m.set('change'.function(){
    console.log("We can change you!!);
});
let key = {
    school : 'ATGUIGU'
};
m.set(key, ['Beijing'.'Shanghai'.'shenzhen']);
// size
console.log(m.size);
/ / delete
m.delete('name');
/ / to get
console.log(m.get('change'));
console.log(m.get(key));
/ / to empty
m.clear();

/ / traverse
for(let v of m){
    console.log(v); // v is an array, the first element is key, the second element is value
}
Copy the code

15. Deep copy, shallow copy, and low-level implementation (hard and hard!)

1. Data type:

  • Data is divided into basic data types (String, Number, Boolean, Null, Undefined) and object data types

    • Basic data types

      Features: Stores the actual data of the object

    • Object data type

      Features: Stores references to the object in the heap. Real data is stored in the heap memory

2. Copy data

  • Primitive data types store actual data and can be copied directly
let number2 = 2;
let number1 = number2;
Copy the code
  • Clone (copy) data: objects/arrays

1- Difference: Shallow copy/deep copy

Determine whether the copy creates new data or copies references to the data

Object data stores references to objects in the heap, and directly copies references to objects

let obj = {username: 'kobe'}
let obj1 = obj;  // obj1 copies a reference to obj in the heap
Copy the code

Note: Deep copy or shallow copy: Does modifying the data after the copy (reference data) affect the original data?

2- Common copying techniques

1).arr. Concat (): shallow copy of array

2).arr.slice (): pass parameter 0, shallow copy array

Parse (json.stringify (arr/obj)): Deep copy of array or object, but cannot handle function data

4). Object.assign(target, source1, source2..) Shallow copy:

5). The extension operator is a shallow copy

Note:

1. Shallow copy of the object/array containing the function data

2. Deep copy the object/array that contains the function data

Example:

1. Implement methods to detect data types

2. Implement deep copy: objects, arrays – recursion (emphasis!)

let obj = {username: 'kobe'};
console.log(obj.toString()); // [object Object]
let arr = [1.2.3];
// Array overrides the toString method of the Object prototype
console.log(arr.toString()); / / 1, 2, 3

console.log(Object.prototype.toString.call(arr)); // [object Array]
// Can be used to detect data types
console.log(Object.prototype.toString.call(null).slice(8, -1)); // Interception type
// Implement methods to detect data types (key!)
function checkoutType(target) {
    return Object.prototype.toString.call(target).slice(8, -1);
}

// for... in
let obj = {username: 'kobe'.age: 43};
for(let item in obj){
    console.log(item);
}
// for in Traverses the array to get the index of the array
for(let item in arr){
    console.log(item);
}

// Deep copy import
// obj stores the memory address of the object
let obj = {username: 'kobe'.age: 43};
let obj2 = obj;  // obj saves the memory address to obj2, passed by reference
obj2.username = 'wade'
console.log(obj.username);

// Basic data types hold the values themselves
let num = 123;
let num2 = num;  // Change the new data without affecting the original data
num2 = 234;
console.log(num);


// Copy: deep copy/shallow copy. Determine whether the deep copy or shallow copy: Modify the copied data (reference data) to ensure that the original data is not affected
let obj = {username: 'kobe'.age: 43};
let obj2 = {};
obj2.username = obj.username;
obj2.age = obj.age;
obj2.username = 'wade';
console.log(obj.username);

// arr.concat(): shallow copy of array
let arr = [1.2.3, {username: 'kobe'}];
let testArr = [4.5];
let arr2 = [];
// arr2 = arr.concat(arr2);
console.log(arr2);

arr2 = arr.concat();
console.log(arr2);
arr2[3].username = 'wade';
console.log(arr, arr2);

// arr.slice(): shallow copy of array
let arr3 = arr.slice(0);
arr3[3].username = 'duncan';
console.log(arr3, arr);


Parse (json.stringify (arr/obj)) converts JSON data to native JS objects/arrays
//json data: JSON object, JSON array
let obj = {username: 'kobe'.age: 43.sex: {option1: 'male'.option2: 'woman'}};  // Cannot handle copies of functions
let obj2 = JSON.parse(JSON.stringify(obj));
console.log(obj2);
obj2.username = 'wade';
obj2.sex.option1  = 'hybrid';
console.log(obj2, obj);


// Object.assign(target, source1, source2..) Shallow copy
let obj = {username: 'kobe'.age: 43.sex: {option1: 'male'.option2: 'woman'}};
let obj2 = {};
Object.assign(obj2, obj);
obj2.username = 'wade';
obj2.sex.option1  = 'hybrid';
console.log(obj2, obj);


// Extension operators are shallow copies
// Extension operators can be used to construct literal objects...
let person = {name:'tom'.age:18.ss: {s:11}}
letperson2 = {... person}//console.log(... person); // The expansion operator cannot expand the object
person2.name = 'jerry';
person2.ss.s = 22;
console.log(person2);
console.log(person);


// Implement deep copy: objects, arrays - Recursion is used
function checkoutType(target) {
    return Object.prototype.toString.call(target).slice(8, -1);
}
function clone(target) {
    let result; // Finally process the copied data
    / / test data types - it copies of the data object is | | array | | other (basic data types, functions)
    let targetType = checkoutType(target);
    if(targetType === 'Array'){
        result = [];
    }else if(targetType === 'Object'){
        result = {};
    }else {
        return target;
    }
    / / copy
    // arr = [1,2,3] ====> []arr2
    // obj = {username: 'kobe'} ===> {}obj2
    for(let item in target){
        // item: key, array, index
        // target[item] can get the corresponding value
        let value = target[item];
        // arr2[item] = arr[item]
        // Check if it is a reference data type
        if(checkoutType(value) === 'Object' || 'Array'){
            result[item] = clone(value);
        }else{ result[item] = value; }}return result;
}

let obj = {username: 'kobe'.age: 43.sex: ['male'.'woman']};
let obj2 = clone(obj);
obj.username = 'wade';
console.log(obj, obj2);
obj2.sex[0] = 'hybrid';
console.log(obj, obj2);
Copy the code

16.ES7 – Exponential operator (powers)

1. Exponent operator (power): **

  • Equivalent of Math. The pow ()

Example:

console.log(3支那3); / / 27
Copy the code

17. The interview questions

/ / 1
var obj = {n: 1};
var obj2 = obj;
obj2.n = 2;
console.log(obj.n); / / 2

/ / 2
function fn1(a) {
	a.n = 3;
}
fn1(obj);
console.log(obj.n); / / 3

/ / 3
function fn2(a) {
    a = {n: 4}
}
fn2(obj);
console.log(obj.n); / / 3


/ / 4
var a = {n: 1};
var b = a;
a.x = a = {n: 2};
console.log(a.n, b.n); 1 / / 2
console.log(a.x, b.x); //undefined {n: 2}Note: Manipulating object properties takes precedence over assigning to the object itself! a.x = a = {n: 2};
    // Break the action above
    a.x = {n: 2};
    a = {n: 2};


/ / 5
var x = 10;
function fn() {
    console.log(x);
}
function show(f) {
    var x = 20;
    f();
}
show(fn); / / 10


/ / 6
var fn = function () {
    console.log(fn);
}
fn(); //function


/ / 7
var obj = {
    fn2: function () {
        console.log(this.fn2); //function
        console.log(fn2); / / an error
}
obj.fn2();


/ / 8
var a = 2;
function fn() {
    console.log(a);
    var a = 3;
}
fn(); //undefined

function fn2() {
    console.log(a)
    a = 3;
fn2() / / 2

    
/ / 9
function b() {}
var b;
console.log(typeof b); //function

    
/ / 10
var c = 1;
function c(c) {
    console.log(c);
    var c = 3;
}
console.log(c); / / 1
c(2); / / an error

    
/ / 11
var name = 'wor1d! '; (function () {
    if (typeof name === 'undefined') {
        var name = 'Jack';
        console.log(name); //Jack
    } else {
        console.log(name)
    }
})()

    
/ / 12
var a = 6;
setTimeout(function () {
    console.log(0);
    alert(a);
    a = Awesome!;
}, 0);
console.log(1);
a = 66;
/ / 1 0 66

    
/ / 13
function fn1() {
	var a = 2;
    function fn2 () {
        a++;
        console.log(a);
    }
    return fn2;
}
var f = fn1();
f(); / / 3
f(); / / 4
Copy the code