ES6 knowledge points - next

ES6 knowledge points - next

Previous portal link: ES6 knowledge points - up.

String API

indexOf ()

Find whether a string contains a substring

Parameter 1: target string to query

Parameter 2: index to start query (0 by default if not written)

Return value: if the index of the first target substring is found, if it is not found, -1 is returned

Note: indexOf is case sensitive

var str="Hello world!"
document.write(str.indexOf("Hello") + "<br />")
document.write(str.indexOf("World") + "<br />")



Detect whether a string or array contains a substring or element

Parameter 1: target string to query

Parameter 2: the index to start the query (if not written, it starts from 0 by default)

Return value: Boolean type returns true if found, false if not found

[1, 2, 3].includes(2);     // true
[1, 2, 3].includes(4);     // false
[1, 2, 3].includes(3, 3);  // false
[1, 2, 3].includes(3, -1); // true
[1, 2, NaN].includes(NaN); // true

Difference between the two

  1. Return value: the indexOf method returns the position index of the first substring found, including. If found, it returns true
  2. If the array contains NaN, but we just need to check whether there is NaN in the array, then indexOf is useless and we can only use includes
  3. If the array contains a null value, an error will occur when using indexOf. You can use includes

Arrow function

The ES6 standard adds a new function: Arrow Function.

Syntax ratio of arrow function expression Function expression It is more concise and does not have its own this, arguments, super or new Target. The arrow function expression is more suitable for those places where anonymous functions are required, and it cannot be used as a constructor.

Basic grammar

Definition method of general function

var fn1 = function(a, b) {

  return a + b


function fn2(a, b) {

  return a + b


Use ES6 arrow function syntax to define a function, delete the "function" keyword and function name of the original function, and use "= >" to connect the parameter list and the function body

  1. When the function body has only one sentence, the return value can be omitted. Return the function body can omit {}
  1. If the arrow function has no parameters or multiple parameters, the () of the parameter cannot be omitted
// No parameter

var fn1 = function() {}

var fn1 = () => {}


// Single parameter

var fn2 = function(a) {}

var fn2 = a => {}


// Multiple parameters

var fn3 = function(a, b) {}

var fn3 = (a, b) => {}


// Variable parameters

var fn4 = function(a, b, ...args) {}

var fn4 = (a, b, ...args) => {}
  1. If there are multiple codes in the function body of the arrow function, {} and return values cannot be omitted
var fn3 = function(a, b) {
    return a+b

var fn3 = (a, b) => {
    return a+b
  1. If the function body has only one sentence and the return value is also the object name, the return value must be wrapped in ()

Because the function body uses {} and the object is also {}

var info = (name,age) => ({
  1. If the object has only one key value pair, no error will be reported, but there is no correct value

Because when the js engine parses {} by default, it resolves to function body structure function body code name:name

var p = (name)=>{


this point in ES6

this point of ordinary function

This means that whoever calls this points to whom this is determined at the time of the call

function a(){
    var user = "Lele";
    console.log(this.user); //undefined
    console.log(this); //Window

The above-mentioned this finally points to the object that calls it. The function a here is actually pointed out by the Window object

Equivalent to window A ()

this in the object points to

The method in the object whose this point is the current object

var o = {
        console.log(this.user);  //Lele

Here, this refers to the object o, because you call this FN through o.fn(), which naturally refers to the object O. but it should be emphasized that the direction of this cannot be determined at the time of function creation. It can only be determined at the time of call. Whoever calls it will point to who. We must be clear about this.

Error demonstration

var o = {
        console.log(this.age);  //NaN

This error demonstration vividly corresponds to the above sentence that the direction of this cannot be determined when the function is created

When the o object is created, this is the age:2020-this This Birth becomes window The birth value is undefined, and the 2020 undefined result is NaN. And it is unrealistic to call the method of the object inside the object.

this in the timer points to

If there is no special point, the setTimeout and setInterval callback functions this must point to the window

this in constructor

Constructor instantiates this of the object

function Fn(){
    this.user = "Lele";
var a = new Fn();
console.log(a.user); //Lele

The reason why object a can point out the user in function Fn is that the new keyword can change the direction of this to point this to object A. why I say that a is an object, because using the new keyword means creating an object instance. Here, we create an instance of Fn with variable a (equivalent to copying a copy of Fn into object a). At this time, it is only created but not executed. Object a calls this function Fn, This naturally points to object A. why is there a user in object a? Because you have copied a copy of the Fn function into object a, using the new keyword is equivalent to copying a copy.

Constructor as this called by ordinary function

function Fn() {
    this.user = "Lele";
    return this.user

Special circumstances

var o = {
            console.log(this.a); //undefined
            console.log(this); //window
var j = o.b.fn;

Here this points to the window. Is it a bit confused? In fact, it's because you don't understand a sentence, which is also very important.

this always points to the object that called it last, that is, it depends on who called it when it was executed. Although the function fn is referenced by object b, it was not executed when FN was assigned to variable j, so it finally points to window.


There are five original types in ES5: character string,number,Boolean value,null and undefined . ES6 introduces the sixth primitive type - Symbol

ES5 object attribute names are all strings, which is easy to cause attribute name conflicts. For example, if you use an object provided by others and want to add a new method to this object, the name of the new method may conflict with the existing method. If there is a mechanism to ensure that the name of each attribute is unique, it will fundamentally prevent attribute name conflicts. This is why ES6 introduces symbols. This article will introduce Symbol types in ES6 in detail


The Symbol value is generated by the Symbol function. That is to say, the attribute name of an object can be of two types: a string and a Symbol. All attribute names that belong to Symbol type are unique, which can ensure that they will not conflict with other attribute names

let firstName = Symbol();
let person = {};
person[firstName] = "train";
console.log(person[firstName]); // "Train"

[note] the new command cannot be used before the Symbol function, otherwise an error will be reported. Because the generated Symbol is a value of the original type, not an object

//Uncaught TypeError: Symbol is not a constructor
let firstName = new Symbol();

The Symbol function accepts an optional parameter. You can add a text to describe the Symbol to be created. This description cannot be used for attribute access. However, it is recommended to add such a description every time you create a Symbol to facilitate code reading and Symbol program debugging

let firstName = Symbol("first name");
let person = {};
person[firstName] = "train";
console.log("first name" in person); // false
console.log(person[firstName]); // "Train"
console.log(firstName); // "Symbol(first name)"

The Description of the Symbol is stored in the internal [[Description]] attribute, which can be read only when the toString() method of the Symbol is called. Execute the console Log() implicitly calls the toString() method of firstName, so its Description will be printed to the log, but you cannot directly access [[Description]]

[type detection]

Symbol is the original value. ES6 extends the typeof operator and returns "symbol". So you can use typeof to detect whether the variable is of symbol type

let symbol = Symbol("test symbol");
console.log(typeof symbol); // "symbol"


Since each Symbol value is not equal, this means that the Symbol value can be used as an identifier for the attribute name of the object, so as to ensure that no attribute with the same name will appear. This is very useful when an object is composed of multiple modules to prevent a key from being accidentally overwritten or overwritten

Symbol can be used wherever computable attribute names are used

let firstName = Symbol("first name");
// Use a literal to be calculated attribute
let person = {
    [firstName]: "train"
// Make this property read-only
Object.defineProperty(person, firstName, { writable: false });
let lastName = Symbol("last name");
Object.defineProperties(person, {
    [lastName]: {
        value: "match",
        writable: false
console.log(person[firstName]); // "Train"
console.log(person[lastName]); // "match"

In this example, a Symbol attribute firstName is first created for the person object through the computable object literal attribute syntax. The next line of code sets this property to read-only. Then, through object The defineproperties () method creates a read-only Symbol property lastName. Here, the object literal property is used again, but it is used as object The second parameter of the defineproperties () method uses

[note] when Symbol value is used as object attribute name, dot operator cannot be used

var mySymbol = Symbol();
var a = {};

a.mySymbol = 'Hello!';
a[mySymbol] // undefined
a['mySymbol'] // "Hello!"

It can be seen from the above results that a.mySymbol and mySymbol in a['mySymbol'] are attribute names of string type, and mySymbol in a[mySymbol] is attribute name of Symbol type. Although they are all called mySymbol, the values are different

Although symbols can be used in all places where computable attribute names are used, in order to effectively share these symbols among different code fragments, a system needs to be established

Sharing system

Sometimes you want to share the same Symbol in different codes. For example, there are two different object types in applications, but you want them to use the same Symbol attribute to represent a unique identifier. In general, it is difficult and error prone to track symbols in a large code base or across files. For these reasons, ES6 provides a global Symbol registry that can be accessed at any time


If you want to create a shareable Symbol, use Symbol For() method. It accepts only one parameter, that is, the string identifier of the Symbol to be created. This parameter is also used as the description of the Symbol

let uid = Symbol.for("uid");
let object = {};
object[uid] = "12345";
console.log(object[uid]); // "12345"
console.log(uid); // "Symbol(uid)"

Symbol The for() method first searches the global symbol registry for the existence of a symbol with the key "uid". If it exists, return the existing symbol directly. Otherwise, create a new symbol and use this key to register in the symbol Global Registry, and then return the newly created symbol

Subsequently, if the same key is passed in, the Symbol For() returns the same Symbol

let uid = Symbol.for("uid");
let object = {
    [uid]: "12345"
console.log(object[uid]); // "12345"
console.log(uid); // "Symbol(uid)"
let uid2 = Symbol.for("uid");
console.log(uid === uid2); // true
console.log(object[uid2]); // "12345"
console.log(uid2); // "Symbol(uid)

In this example, uid and uid2 contain the same Symbol and can be used interchangeably. First call Symbol The for () method creates the Symbol, and the second call can directly retrieve the Symbol from the global registry of the Symbol

Set() constructor

About the Set() function

Set is a constructor, which is similar to an array, but the elements are not duplicated

  1. Receive data from arrays or other iterable interfaces for initialization
let a=new Set([1,32,424,22,12,3,2,2,1]);
console.log(a)//[ 1, 32, 424, 22, 12, 3, 2 ]
  1. Implement array de duplication
let b=[1,2,3,4,51,51,2,23,2];
let c=new Set(b);
console.log(b);//[ 1, 2, 3, 4, 51, 23 ]
  1. The default NANs in the Set are equal and follow '= ='
let d=new Set();

Method of Set()

  1. add() adds a member and returns the set structure itself

  2. delete() deletes a member and returns bool

  3. has() determines whether there is an element in it and returns bool

  4. clear() knows all members and does not return a value

let e=new Set();
let f=e.add(1);
console.log(e,f);//[1] [1]
let g=f.has(1);
let h=f.delete(3);
console.log(h,f)//true [1]

Array From() can convert a set to an array

let i=new Set([1,2,3,4,5]);
console.log(;//[object Array]

traversal method






let a=new Set([11,22,33,44]);
for(let i of a){
}// 11 22 33 44
for(let i of a.values()){
}//11 22 33 44
for(let i of a.keys()){
}//11 22 33 44
for(let i of a.entries()){
}//[11,11] [22,22] [33,33] [44,44]
})//11 11   22 22  33 33  44 44

Tags: ECMAScript

Posted by leoo24 on Tue, 31 May 2022 15:44:37 +0530