Advanced JavaScript - Getting Started with ES6 Basics

foreword

ES6 (ECMAScript 6), also known as ES2015, is the sixth version of JavaScript. It was released in 2015 and has played an important role in modern JavaScript development.

study method:

  • It is better to write it yourself than to read it a thousand times
  • Don't be afraid when you encounter problems, face it with a smile
  • take notes

let and const

  • const and let are two new variable declaration keywords introduced in ES6, which are used to declare the scope of variables.
  1. const: const is used to declare a constant whose value cannot be modified after declaration . Constants must be initialized at declaration time and cannot be reassigned. For example:

    const PI = 3.14159;
    PI = 3.14; // 报错,常量不能再次赋值
    
  • Constants are suitable for storing immutable values, such as mathematical constants, configuration items, etc.
  1. let: let is used to declare variables with block-level scope, which has a smaller scope than var. Variables declared inside a block-level scope are only valid within that block-level scope and will not be promoted to function scope. For example:

    function example() {
          
          
      let x = 10;
      if (true) {
          
          
        let x = 20;
        console.log(x); // 输出 20
      }
      console.log(x); // 输出 10
    }
    
  • When using block-level scope, you can avoid naming conflicts and problems between variables.
  1. var: var is a variable declaration keyword used in ES5, which has some scope problems. Variables declared by var belong to function scope or global scope , not block-level scope, so variables declared in loops or conditional statements will be promoted to the outer function scope.

    function example() {
          
          
      var x = 10;
      if (true) {
          
          
        var x = 20;
        console.log(x); // 输出 20
      }
      console.log(x); // 输出 20,而不是 10
    }
    
  • The variable declared by var has the problem of variable promotion, and the variable can be accessed before the variable declaration, which may lead to unexpected results.

block scope

  • Block-level scope refers to the part surrounded by curly braces {} in the code . The variables declared inside this part are only valid in the block-level scope, and cannot be accessed outside the scope. Before ES6, JavaScript only had global scope and function scope, but no block-level scope.

  • Using block-level scope can provide a finer-grained variable scope and avoid variable conflicts and pollution. Block-level scope can be used for code blocks in statements such as if statements, for loops, while loops, and code blocks in functions.
    insert image description here


template string

1. What is a template string

Template strings are a special string syntax used in JavaScript. It is surrounded by backticks (`) and allows interpolation of variables, expressions, newlines, etc. within the string. Here are some characteristics of template strings:

  1. Insert variables: By ${}syntax, variables can be inserted in the string. Variables are parsed and replaced with actual values. The sample code is as follows:

    const name = "Alice";
    const message = `Hello, ${
            
            name}!`;
    console.log(message); // 输出 "Hello, Alice!"
    
  2. Executing expressions: In ${}addition to inserting variables, expressions can also be executed. This enables complex arithmetic or logical operations on strings. The sample code is as follows:

    const a = 10;
    const b = 5;
    const result = `The sum of ${
            
            a} and ${
            
            b} is ${
            
            a + b}.`;
    console.log(result); // 输出 "The sum of 10 and 5 is 15."
    
  3. Multi-line strings: Newline characters can be used directly in template strings to facilitate the creation of multi-line text. The sample code is as follows:

    const multiLine = `This is a 
    multi-line
    string.`;
    console.log(multiLine);
    // 输出:
    // This is a
    // multi-line
    // string.
    

Template strings are more flexible and readable, making operations on strings easier. It is especially useful in combination with variables and expressions.

2. Precautions for template strings

  1. Backtick (`) Surrounding: Template strings must be surrounded by backticks (`) rather than single or double quotes.

  2. Insertion in String: Use ${}to wrap variables or expressions to be inserted. Note that ${}any valid JavaScript expression can be used in . However, be careful not to put code with side effects in there, which can produce unexpected results.

  3. Escape character: If you need to use backticks (`) in the string, you need to use the escape character (\) to escape.

  4. Newline characters: Newline characters in template strings are preserved. If you want the string to wrap, use an explicit newline (\n).

  5. Nested Template Strings: Template strings can be nested within each other to create more complex string structures.

  6. Compatibility: Template strings are a feature introduced in ES6, so may not be fully supported in older browsers or environments. For compatibility, you can use a translation tool (such as Babel) to convert template strings to ordinary strings.

3. Application of template strings

  1. String concatenation: Using template strings makes string concatenation easier, especially when variables need to be inserted or expressions executed. Template strings are more concise and readable than traditional string concatenation methods (using the plus sign or the concat function).

  2. Dynamic HTML Generation: HTML fragments containing dynamic data can be dynamically generated by inserting variables or expressions into template strings. This is useful for generating complex HTML structures based on data, dynamically updating web page content, etc.

  3. URL splicing: When building URLs, template strings can be conveniently inserted into parameter values ​​to generate a complete URL.

  4. Multilingual support: In a multilingual environment, template strings can be used to create multilingual text templates, and translations for corresponding languages ​​can be inserted as needed.

  5. Formatted output: By using placeholders and formatting rules in the template string, you can control the formatting of the output results, such as date formatting, currency formatting, etc.

  6. Generating code: In some cases, template strings can be used to generate dynamic JavaScript code. For example, generate dynamic function definitions based on user input.


arrow function

1. What is an arrow function

  • Concept: Arrow function is a new function declaration syntax introduced in ES6 (ECMAScript 2015). It provides a more concise and clearer way of defining functions.

  • grammar:

(argument1, argument2, ...) => {
    
    
  // 函数体
}

Here, the parameter list is surrounded by parentheses, followed by an arrow (=>), and then the function body (which can be a code block or an expression).

  • Features of arrow functions:

    1. Concise syntax: Compared with regular functions, arrow functions provide a more concise syntax and reduce redundant code.

    2. No own this value: The arrow function does not have its own thiscontext, and inherits thisthe value of the parent scope. This solves thisthe problem of pointing in regular functions, making arrow functions easier to understand and use.

    3. Does not have its own arguments object: Arrow functions also do not have their own objects, but you can get all the arguments passed to the function argumentsby using restarguments( )....args

    4. thisNo Constructor: Arrow functions cannot be used as constructors to create object instances due to having no own value, i.e. newarrow functions cannot be called using keywords.

  • Example:

    const add = (a, b) => {
          
            //或者const add = (a, b) => a +b ;
      return a + b;
    };
    
    const greet = name => `Hello, ${
            
            name}!`;
    
    const numbers = [1, 2, 3, 4];
    const doubled = numbers.map(num => num * 2);
    

2. Conversion of ordinary functions and arrow functions

  1. Determine whether the function has parameters. If there are parameters, you need to use parentheses to wrap the parameter list. Parentheses can be omitted if there is only one parameter.

    // 普通函数
    function sum(a, b) {
          
          
      return a + b;
    }
    
    // 转换为箭头函数
    const sum = (a, b) => a + b;
    
  2. The keyword is removed functionand an arrow ( ) is added between the parameter and the arrow =>.

    // 普通函数
    function sayHello() {
          
          
      console.log("Hello!");
    }
    
    // 转换为箭头函数
    const sayHello = () => {
          
          
      console.log("Hello!");
    };
    
  3. If the function body is only one line of code, and it is an expression, you can omit the curly braces and returnkeywords, and put the expression after the arrow.

    // 普通函数
    function square(x) {
          
          
      return x * x;
    }
    
    // 转换为箭头函数
    const square = (x) => x * x;
    
  4. If the function has only one return value and no parameters, you can use implicit return, that is, omit the curly braces and returnkeywords, and put the return value after the arrow.

    // 普通函数
    function getPi() {
          
          
      return 3.14;
    }
    
    // 转换为箭头函数
    const getPi = () => 3.14;
    
  • Notice:
    • Arrow functions do not have their own thisbindings, they capture thisthe value in the outer scope, so pay special attention to whether keywords are used inside the function when converting the function this.

    • In some special cases, where more complex function bodies are required or argumentsobjects need to be used, arrow functions may not be suitable for conversion, because they lack some features of regular functions.

3.this points to

1. in the global scope thispoints to

  • In strict mode, thisthe value of at the global scope is undefined. In non-strict mode, it points to the global object ( object in browsers window, object in Node.js global).

    • Use of strict mode can be enabled by adding at the beginning of the script file or function body "use strict";. The following example demonstrates thisthe behavior of in global scope in strict mode:
    "use strict";
    
    console.log(this); // undefined
    
  • In non-strict mode, the global object is output:

    console.log(this); // 全局对象(浏览器中是window对象,Node.js中是global对象)
    

2. The this point in the general function (non-arrow function)

  • In an object's method, even in strict mode, the in the method thiswill still point to the object that called the method. thisStrict mode primarily affects the behavior of values ​​at the global scope .

    "use strict";
    
    const obj = {
          
          
      name: "Alice",
      sayHello: function() {
          
          
        console.log(this); // 指向obj对象
      }
    };
    
    obj.sayHello();
    
  • thisPoints to the newly created object in strict mode if the object is created via a constructor . But in non-strict mode, if there is no thisvalue explicitly set inside the constructor, then thismay point to the global object.

3. The arrow function thispoints to

  • In an arrow function, thisthe value of is determined by the lexical scope in which the arrow function is defined, not by how the function is called or who is bound to the caller.

  • In other words, an arrow function does not have its own thisbinding, it captures thisthe value of in the lexical scope outside it, and inherits that value. Therefore, inside the arrow function, thisthe pointer to is fixed, pointing to the scope where the arrow function was defined this.

  • Example:

    • Object method:

      const obj = {
              
              
        name: "Alice",
        sayHello: () => {
              
              
          console.log(this.name); // 箭头函数没有自己的 this,沿用外部作用域中的 this,这里指向全局对象(浏览器中是 window,Node.js 中是 global)
        }
      };
      
    • Binding in the callback function this:

      const button = document.querySelector("button");
      button.addEventListener("click", () => {
              
              
        console.log(this); // 箭头函数没有自己的 this,沿用外部作用域中的 this,取决于事件处理函数所在的上下文
      });
      

4. Scenarios where arrow functions are not applicable

  1. as a constructor

    • Since an arrow function does not have its own thisbinding, it cannot newcreate an instance object through the keyword. An arrow function's thisalways points to the value in its outer lexical scope this, and doesn't change depending on how it's called or who it's bound to.

      // 错误示例
      const Person = () => {
              
              
        this.name = "Alice"; // 错误:箭头函数不能用作构造函数
      };
      
      const person = new Person();
      
  2. Cases that need to thispoint to the calling object

    • Object method : Arrow functions are not applicable when you need to define a method in an object and you need to refer to the object itself through ​this​. The ​this​ of an arrow function is always inherited from the outer lexical scope and cannot be dynamically bound according to the calling method.

      const obj = {
              
              
        name: "Alice",
        sayHello: () => {
              
              
          console.log(`Hello, ${
                
                this.name}!`); // 错误:箭头函数的 this 不是指向 obj
        }
      };
      
      
    • Dynamic binding of ​this ​: If you need to dynamically bind the value of ​this​ depending on the calling method, such as explicitly changing its value through call(), apply()or , then arrow functions are not suitable for use. The ​this​ of an arrow function always remains the same.bind()this

      
      const greet = () => {
              
              
        console.log(`Hello, ${
                
                this.name}!`); // 错误:箭头函数的 this 不会被显式绑定
      };
      
      const person = {
              
              
        name: "Alice"
      };
      
      greet.call(person); // 错误:this 在箭头函数中不会改变
      
      
  3. argumentsThe object that needs to use the function

    • Arrow functions do not have their own argumentsobject and cannot access the set of parameters passed to the function.

      const sum = () => {
              
              
        console.log(arguments); // 错误:箭头函数没有自己的 arguments 对象
      };
      
      sum(1, 2, 3); // 错误:无法在箭头函数中访问 arguments
      

Five. The application of arrow function

  1. Simplified function expressions: Arrow functions provide a more concise function expression syntax, especially useful for passing anonymous functions or callback functions.

    // 传统函数表达式
    const sum = function(a, b) {
          
          
      return a + b;
    };
    
    // 箭头函数
    const sum = (a, b) => a + b;
    
  2. Array traversal and conversion: Combining with methods such as array map(), filter()and , you can use arrow functions to quickly traverse, filter and convert arrays.reduce()

    const numbers = [1, 2, 3, 4, 5];
    
    const doubled = numbers.map(num => num * 2);
    
    const evenNumbers = numbers.filter(num => num % 2 === 0);
    
    const sum = numbers.reduce((total, num) => total + num, 0);
    
  3. Arrow functions as callback functions: Since arrow functions do not have their own thisvalue, they are often used to solve thisproblems pointed to in callback functions.

    const obj = {
          
          
      name: "Alice",
      sayHello: function() {
          
          
        setTimeout(() => {
          
          
          console.log(`Hello, ${
            
            this.name}!`); // this指向obj对象
        }, 1000);
      }
    };
    
    obj.sayHello();
    
  4. More concise function nesting: When you need to define a function inside another function, you can use arrow functions to simplify the syntax.

    function foo() {
          
          
      return (a, b) => a + b;
    }
    
    const add = foo();
    console.log(add(2, 3)); // 5
    
  5. Concise definition of object methods: When defining object methods, arrow functions can be used to simplify the syntax.

    const obj = {
          
          
      name: "Alice",
      sayHello: () => {
          
          
        console.log(`Hello, ${
            
            this.name}!`); // this指向全局对象
      }
    };
    
    obj.sayHello();
    

destructuring assignment

Destructuring is a way of extracting a value from an array or object and assigning it to a variable.

1. Array destructuring assignment

  • principle:
    • Array destructuring assignments are assigned according to the index position through pattern matching .
    • When doing destructuring assignment, you can directly assign an array [] to the pattern on the left side of the equal sign.
    • Default values ​​can be used to specify missing element values.
  • Sample code:
    // 基本用法
    const [a, b, c] = [1, 2, 3];
    console.log(a); // 输出: 1
    console.log(b); // 输出: 2
    console.log(c); // 输出: 3
    
    // 使用默认值
    const [x, y, z = 0] = [4, 5];
    console.log(x); // 输出: 4
    console.log(y); // 输出: 5
    console.log(z); // 输出: 0(默认值)
    

2. Object destructuring assignment

  • principle:

    • Object destructuring assignment is done through pattern matching , and assignment is performed according to the attribute name .
    • When doing destructuring assignment, you can directly assign an object {} to the pattern on the left side of the equal sign.
    • Default values ​​can be used to specify missing attribute values.
  • Sample code:

    // 基本用法
    const {
          
          name, age} = {
          
          name: "Alice", age: 20};
    console.log(name); // 输出: "Alice"
    console.log(age); // 输出: 20
    
    // 使用别名
    const {
          
          name: personName, age: personAge} = {
          
          name: "Bob", age: 25};
    console.log(personName); // 输出: "Bob"
    console.log(personAge); // 输出: 25
    
    // 使用默认值
    const {
          
          firstName = "Unknown", lastName = "Unknown"} = {
          
          firstName: "Charlie"};
    console.log(firstName); // 输出: "Charlie"
    console.log(lastName); // 输出: "Unknown"(默认值)
    
  • Precautions:

    • Use an already declared variable for destructuring assignment, the entire assignment needs to be done in parentheses

      • Because the JavaScript parser will parse the statement starting with the left curly brace { as a code block, not an object literal. To avoid this ambiguity, you can enclose a destructuring assignment expression in parentheses to explicitly tell the parser that it is an assignment expression.

        let x, y;
        
        // 错误的写法:解析为代码块
        {
                  
                  x, y} = {
                  
                  x: 1, y: 2};
        
        // 正确的写法:圆括号中进行解构赋值
        ({
                  
                  x, y} = {
                  
                  x: 1, y: 2});
        
        console.log(x,y); // 输出: 1 2
        
        
    • The destructuring assignment of the object can get the inherited property or method

      • When performing object destructuring assignment, if the attribute of the target object does not exist, the destructuring assignment expression will continue to look up the attribute; if the attribute of the target object exists in the prototype chain, the value of the attribute can be successfully extracted.
      function Person(name) {
              
              
        this.name = name;
      }
      
      Person.prototype.sayHello = function() {
              
              
        console.log(`Hello, ${
                
                this.name}!`);
      };
      
      function Student(name, grade) {
              
              
        Person.call(this, name);
        this.grade = grade;
      }
      
      Student.prototype = Object.create(Person.prototype);
      Student.prototype.constructor = Student;
      Student.prototype.study = function() {
              
              
        console.log(`${
                
                this.name} is studying in grade ${
                
                this.grade}.`);
      };
      
      const student = new Student('Alice', 10);
      
      // 对象解构赋值取到继承的属性
      const {
              
               name, grade } = student;
      console.log(name); // 输出: "Alice"
      console.log(grade); // 输出: 10
      
      // 解构赋值取到继承的方法
      const {
              
               sayHello, study } = student;
      sayHello(); // 输出: "Hello, Alice!"
      study(); // 输出: "Alice is studying in grade 10."
      

3. Destructuring assignment of other data types

  • Destructuring assignment of strings: Strings can be deconstructed and assigned according to characters.

    const [a, b, c] = 'abc';
    console.log(a); // 输出: 'a'
    console.log(b); // 输出: 'b'
    console.log(c); // 输出: 'c'
    
  • Destructuring assignment of numeric and Boolean values: the numeric and Boolean values ​​will be converted to the corresponding wrapping object types (Number, Boolean), and then the destructuring assignment will be performed.
    Sample code:

    const {
          
          toString: numToString} = 123;
    console.log(numToString === Number.prototype.toString); // 输出: true
    
    const {
          
          valueOf: boolValueOf} = true;
    console.log(boolValueOf === Boolean.prototype.valueOf); // 输出: true
    
  • Undefined and null destructuring assignments: When destructuring assignments, if the source value is undefined or null, the default value will be used.
    Sample code:

    const [x = 0, y] = [undefined, 2];
    console.log(x); // 输出: 0(默认值)
    console.log(y); // 输出: 2
    
    const {
          
          z = 'default'} = {
          
          z: null};
    console.log(z); // 输出: null(原始值)
    

Note: In destructuring assignment, if the target has no corresponding value, you can use default value to specify the default value. And undefined and null cannot be destructured and assigned.


Object Literal Enhancements

1. Concise representation of properties and methods

  1. Object literal : A way to create and initialize an object , use curly braces {}to define an object, and specify the properties and methods of the object through key-value pairs.

  2. Concise notation for properties : When the key name of the property is the same as the variable name, you can use the concise notation to define the property. The concise notation directly uses the variable name as the property name, and automatically uses the variable's value as the property value.

    const name = 'Alice';
    const age = 25;
    
    const person = {
          
          
      name,   //使用简洁表示法将变量 `name` 和 `age` 直接作为对象 `person` 的属性
      age
    };
    
    console.log(person.name); // 输出: "Alice"
    console.log(person.age); // 输出: 25
    
  3. Concise notation for methods : In object literals, you can use function literals to define methods on an object. When using concise notation, you can omit the colon and the function keyword, and directly use the function body as the value of the method . The sample code is as follows:

    const person = {
          
          
      name: 'Alice',
      sayHello() {
          
          
        console.log(`Hello, my name is ${
            
            this.name}`);
      }
    };
    
    person.sayHello(); // 输出: "Hello, my name is Alice"
    

2. Square bracket notation

  • Square bracket notation is a syntax for accessing object properties, using square brackets []to refer to property names or computed properties . This notation enables dynamically getting and setting properties of an object.

  • usage:

    1. Attribute access : Through square bracket notation, you can use variables or expressions as attribute names to dynamically obtain object attribute values . The sample code is as follows:

      const obj = {
              
              
        name: 'Alice',
        age: 25
      };
      
      const propertyName = 'name';
      
      console.log(obj[propertyName]); // 输出: "Alice"
      
    2. Dynamic property names : The square bracket notation can also be used to dynamically set the property names of an object , even if the property names are computed from variables or expressions.

      const obj = {
              
              };
      
      const propertyName = 'name';
      
      obj[propertyName] = 'Alice';
      
      console.log(obj.name); // 输出: "Alice"
      
  • Note: When accessing properties using square bracket notation, the property name can be any string or expression that can be converted to a string. Property names enclosed in square brackets are parsed as strings to match against properties of the object.


Default values ​​for function parameters

  • Concept: When defining a function, provide a default initial value for the parameter. In this way, if the value of the corresponding parameter is not passed when calling the function, the default value can be used as the value of the parameter.

  • Usage: The default value of a function parameter can be set directly within the parentheses of the function definition, using the =operator to specify the default value. Examples are as follows:

    function greet(name = 'Alice') {
          
          
      console.log('Hello, ' + name);
    }
    
    greet(); // 输出: "Hello, Alice"
    greet('Bob'); // 输出: "Hello, Bob"
    
  • Note: The application of the default value of the parameter is lazy evaluation, that is, the default value will be recalculated every time the function is called.

    1. Conditions for the default value to take effect:

      • The default value will only undefinedtake effect when the parameter value is . If an argument is passed but not undefined(eg null, an empty string, etc.), the default value will not take effect.
      • When no corresponding parameter is passed (that is, no parameter value is provided), the default value will take effect.
      function greet(name = 'Alice') {
              
              
        console.log('Hello, ' + name);
      }
      
      greet(); // 默认值生效,输出: "Hello, Alice"
      greet(undefined); // 默认值生效,输出: "Hello, Alice"
      greet(null); // 默认值不生效,输出: "Hello, null"
      greet('Bob'); // 默认值不生效,输出: "Hello, Bob"
      
    2. Default value expression:

      • The default value can be any legal expression, including calling functions, ternary operators, mathematical operations, etc.
      • Default value expressions are evaluated when the function is defined, not each time the function is called.
      function getDefaultValue() {
              
              
        console.log('Calculating default value...');
        return 'Default Value';
      }
      
      function func(param = getDefaultValue()) {
              
              
        console.log('Param:', param);
      }
      
      // 只有没有传递参数时,才会计算默认值
      func(); // 输出: "Calculating default value...","Param: Default Value"
      
      // 传递参数时,不计算默认值
      func('Custom Value'); // 输出: "Param: Custom Value"
      
    3. Tips for setting default values:

      • Default values ​​for function parameters, preferably set from the right side of the parameter list

      • Default values ​​can use the default values ​​of function parameters or other local variables.

      • ||Default values ​​can be provided by using logical operators such as , if the left operand is undefined, then return the right operand.

      // 使用其他局部变量作为默认值
      function combineStrings(str1, str2 = '') {
              
              
        const combinedString = str1 + ' ' + str2;
        console.log(combinedString);
      }
      
      combineStrings('Hello'); // 输出: "Hello "
      combineStrings('Hello', 'world!'); // 输出: "Hello world!"
      
      // 使用逻辑运算符设置默认值
      function greet(name) {
              
              
        name = name || 'Anonymous';
        console.log('Hello, ' + name);
      }
      
      greet(); // 输出: "Hello, Anonymous"
      greet('Alice'); // 输出: "Hello, Alice"
      
  • Application of Default Values ​​for Function Arguments

      // 接收一个对象作为参数
      const logUser = ({
          
          usename = 'zhangsan',age = 0,sex = 'male'}={
          
          })=>console.log(usename,age,sex);
      logUser(); // 输出: zhangsan 0 male
    

remaining parameters

  • Rest Parameters (Rest Parameters) is a syntax introduced in ES6, which is used to declare that a function receives a variable number of parameters and represents these parameters as an array. Remaining parameters are indicated in the function parameter list using three dots (…).
  1. Syntax:
    In a function definition, use three dots (…) followed by a parameter name to declare the remaining parameters.

    function myFunction(...args) {
          
          
      // 函数体
    }
    
  2. Usage example:
    Remaining parameters represent all redundant parameters passed to the function in the form of an array.

    function sum(...numbers) {
          
          
      let total = 0;
      for (let i = 0; i < numbers.length; i++) {
          
          
        total += numbers[i];
      }
      return total;
    }
    
    console.log(sum(1, 2, 3, 4, 5)); // 输出: 15
    
  3. Used in conjunction with other parameters:
    The remaining parameter can be used with other parameters, but must be the last parameter.

    function greet(greeting, ...names) {
          
              // greet() 函数接收一个 `greeting` 参数和多个 `names` 参数。剩余参数 `names` 表示除第一个参数之外的所有其他参数,并将它们存储在一个数组中
      console.log(greeting + " " + names.join(", "));
    }
    
    greet("Hello", "Alice", "Bob", "Carl"); // 输出: Hello Alice, Bob, Carl
    

spread operator

The Spread Operator is a syntax introduced in ES6 to spread an array or object into . The spread operator is prefixed with three dots (...).

Following is the usage of spread operator:

  1. Expanding arrays:
    In scenarios such as function calls, array literals, and array destructuring assignments, you can use the expansion operator to expand the array into independent elements.

    const numbers = [1, 2, 3];
    console.log(...numbers); // 输出: 1 2 3
    
    const sum = (a, b, c) => a + b + c;
    console.log(sum(...numbers)); // 输出: 6
    
  2. Merging arrays:
    You can also merge multiple arrays into a new array using the spread operator.

    const arr1 = [1, 2, 3];
    const arr2 = [4, 5, 6];
    const mergedArray = [...arr1, ...arr2];
    console.log(mergedArray); // 输出: [1, 2, 3, 4, 5, 6]
    
  3. Copying Arrays or Objects:
    The spread operator can be used to shallow copy arrays or objects.

    const originalArray = [1, 2, 3];
    const newArray = [...originalArray];
    console.log(newArray); // 输出: [1, 2, 3]
    
    const originalObject = {
          
           a: 1, b: 2 };
    const newObject = {
          
           ...originalObject };
    console.log(newObject); // 输出: { a: 1, b: 2 }
    
  4. Combining object properties:
    In object literals, the spread operator can be used to combine properties of multiple objects.

    const obj1 = {
          
           a: 1, b: 2 };
    const obj2 = {
          
           c: 3, d: 4 };
    const mergedObject = {
          
           ...obj1, ...obj2 };
    console.log(mergedObject); // 输出: { a: 1, b: 2, c: 3, d: 4 }
    

Note: The spread operator is useful for shallow copying (first level) of arrays and objects. If the unwrapped array or object contains nested reference-type data, only the reference is copied instead of creating a new independent instance.

set and map data structures

  • Set and Map are two new data structures introduced in ES6 for storing and managing data . They can handle uniqueness requirements, key-value pair requirements, deduplication requirements, etc., and are suitable for many practical scenarios, such as data filtering, data mapping, and cache management
  1. Set data structure:
    Set is an ordered and unique collection whose values ​​can be of any type.
    The values ​​in the Set are not repeated, and duplicate values ​​will be automatically deduplicated.

    Common Set operation methods are as follows:

    • add(value): Add a value to the Set.
    • delete(value): Deletes the value specified in the Set.
    • has(value): Check if the Set contains the specified value.
    • size: Returns the number of elements in the Set.
    • clear(): Clear all elements in the Set.
    const mySet = new Set();
    
    mySet.add(1);
    mySet.add(2);
    mySet.add(3);
    mySet.add(2); // 重复值不会被添加
    
    console.log(mySet); // 输出: Set {1, 2, 3}
    console.log(mySet.has(2)); // 输出: true
    console.log(mySet.size); // 输出: 3
    
    mySet.delete(2);
    console.log(mySet); // 输出: Set {1, 3}
    
    mySet.clear();
    console.log(mySet); // 输出: Set {}
    
  2. Map data structure:
    Map is an ordered list for storing key-value pairs , where the key is unique and the value can be of any type.

    Common Map operations are as follows:

    • set(key, value): Add a key-value pair to the Map.
    • get(key): Get the value of the specified key.
    • delete(key): Delete the key-value pair for the specified key.
    • has(key): Check if the specified key is contained in the Map.
    • size: Returns the number of key-value pairs in the Map.
    • clear(): Clear all key-value pairs in the Map.
    const myMap = new Map();
    
    myMap.set('name', 'Alice');
    myMap.set('age', 25);
    myMap.set('gender', 'female');
    myMap.set('name', 'Bob'); // 覆盖已有的键值对
    
    console.log(myMap); // 输出: Map(3) {"name" => "Bob", "age" => 25, "gender" => "female"}
    console.log(myMap.get('age')); // 输出: 25
    console.log(myMap.size); // 输出: 3
    
    myMap.delete('gender');
    console.log(myMap); // 输出: Map(2) {"name" => "Bob", "age" => 25}
    
    myMap.clear();
    console.log(myMap); // 输出: Map {}
    

Iterators and for...of loops

Iterators and loops are mechanisms for...ofin JavaScript for traversing data structures .

  1. Iterator:
    An iterator is an interface that provides a uniform way to iterate over elements in a data structure . It can be used to iterate over objectsArray、String、Set、Map 、NodeList、arguments such as Iterables - objects with built-in symbol methods.​[Symbol.iterator]()​

    • Traversers have a next()method that returns an object containing two properties value, and , each time it is called.done
    • valueIndicates the currently traversed value.
    • doneIndicates whether the traversal is over. The result is a boolean value, done: truewhen the end
    const iterable = [1, 2, 3];
    const it = iterable[Symbol.iterator]();
    
    console.log(it.next()); // 输出: { value: 1, done: false }
    console.log(it.next()); // 输出: { value: 2, done: false }
    console.log(it.next()); // 输出: { value: 3, done: false }
    console.log(it.next()); // 输出: { value: undefined, done: true }  
    
  2. for...ofLoop:
    for...ofA loop is a syntactic construct for traversing iterable objects that support traversers, such as arrays, strings, sets, maps, nodelists, arguments.

    const iterable = [1, 2, 3];
    for (let item of iterable) {
          
          
      console.log(item);
    }
    // 输出: 1
    //       2
    //       3
    

    In for...ofa loop, each iteration automatically calls the iterable's iterator's next()method, and assigns the returned valueto the loop variable (here item). The loop stops when the iterator returns { done: true }indicating the end of traversal.

ES6 new method

1. New method of string

  1. startsWith(searchString, position)And endsWith(searchString, endPosition): Determine whether a string starts or ends with the specified character, and can specify the start position or end position.

    const str = "Hello, world!";
    console.log(str.startsWith("Hello")); // 输出: true
    console.log(str.endsWith("world!")); // 输出: true
    
  2. includes(searchString, position): Determine whether a character string contains the specified character, and specify the starting position.

    const str = "Hello, world!";
    console.log(str.includes("o")); // 输出: true
    
  3. repeat(count): Copy and concatenate a string a specified number of times.

    const str = "Hello";
    console.log(str.repeat(3)); // 输出: HelloHelloHello
    
  4. padStart(targetLength, padString)And padEnd(targetLength, padString): Pad to the specified length at the beginning or end of the string with specified characters.

    const str = "Hello";
    console.log(str.padStart(8, "X")); // 输出: XXXHello
    console.log(str.padEnd(8, "X")); // 输出: HelloXXX
    
  5. ​​​​:trim()​ Delete the spaces at the beginning and end of the string, often used for form submission

    const str = "  Hello, world!  ";
    console.log(str.trim()); // 输出: "Hello, world!"
    

2. New method of array

  1. from(arrayLike, mapFn, thisArg): Converts an array-like object or iterable object into a real array.

    const arr1 = Array.from("hello");
    console.log(arr1); // 输出: ["h", "e", "l", "l", "o"]
    
    const arr2 = Array.from([1, 2, 3], x => x * 2);
    console.log(arr2); // 输出: [2, 4, 6]
    
  2. find(callback, thisArg): Return the first element in the array that meets the condition; findIndex(callback, thisArg): Return the index of the first element in the array that meets the condition.

    const arr = [5, 12, 8, 130, 44];
    const found = arr.find(element => element > 10);
    console.log(found); // 输出: 12
    console.log(foundIndex); // 输出: 1
    
  3. includes(valueToFind, fromIndex): Determine whether the array contains the specified element.

    const arr = [1, 2, 3, 4, 5];
    console.log(arr.includes(3)); // 输出: true
    
  4. fill(value, start, end): Fills all elements of the array with the specified value.

    const arr = [1, 2, 3, 4, 5];
    arr.fill(0);
    console.log(arr); // 输出: [0, 0, 0, 0, 0]
    

3. New method of object

  1. Object.assign(target, ...sources): Used to copy the properties of one or more source objects to the target object. It returns the target object.

    const target = {
          
           a: 1 };
    const source = {
          
           b: 2, c: 3 };
    
    const result = Object.assign(target, source);
    console.log(result); // 输出: { a: 1, b: 2, c: 3 }
    
  2. Object.keys(obj): Returns an array containing the names of the given object's own enumerable properties.

    const obj = {
          
           name: "John", age: 30, gender: "male" };
    const keys = Object.keys(obj);
    console.log(keys); // 输出: ["name", "age", "gender"]
    
  3. Object.values(obj): Returns an array containing the values ​​of the given object's own enumerable properties.

    const obj = {
          
           name: "John", age: 30, gender: "male" };
    const values = Object.values(obj);
    console.log(values); // 输出: ["John", 30, "male"]
    
  4. Object.entries(obj): Returns an array containing key-value pairs of the given object's own enumerable properties.

    const obj = {
          
           name: "John", age: 30, gender: "male" };
    const entries = Object.entries(obj);
    console.log(entries); // 输出: [["name", "John"], ["age", 30], ["gender", "male"]]
    
  5. Object.freeze(obj): Freeze an object so that its properties cannot be modified, added or deleted. This method returns the frozen object.

    const obj = {
          
           name: "John" };
    Object.freeze(obj);
    
    obj.age = 30;
    console.log(obj); // 输出: { name: "John" }
    

Guess you like

Origin blog.csdn.net/weixin_40845165/article/details/131987046