1. ES6 Related Concepts (★★)

1.1 What is ES6

ES stands for ECMAScript, which is a standard specification for scripting languages developed by the ECMA International Standardization Organization. ES6 is a generic term for ES2015

1.2 Why use ES6?

The birth of every standard means the perfection of language and the strengthening of functions. The JavaScript language itself leaves some things to be desired.

  • The variable promotion feature increases the unpredictability of program runtime
  • Syntax is too loose and different people may write different code for the same function

2. New syntax in ES6

2.1 let (★★★)

Keywords for declaring variables have been added to ES6

Variables declared by the LET are only valid at the block level

 if (true) { 
     let a = 10;
 }
console.log(a) // a is not defined
Copy the code

Note: Variables declared using the let keyword have block-level scope. Variables declared using var do not have block-level scope.

There is no variable promotion

console.log(a); // a is not defined 
let a = 20;
Copy the code

Temporary dead zone

Variables declared using let are bound to this block-level scope, unaffected by the outside world

 var tmp = 123;
 if (true) { 
     tmp = 'abc';
     let tmp; 
 } 
Copy the code

Classic Interview questions

 var arr = [];
 for (var i = 0; i < 2; i++) {
     arr[i] = function () {
         console.log(i); 
     }
 }
 arr[0] (); arr[1] ();Copy the code

The key point of this question is that the variable I is global, and the output of this function is the value of I in the global scope.

 let arr = [];
 for (let i = 0; i < 2; i++) {
     arr[i] = function () {
         console.log(i); 
     }
 }
 arr[0] (); arr[1] ();Copy the code

The key point of this question is that each loop generates a block-level scope. The variables in each block-level scope are different, and the function is executed to output the value of I in its upper (the block-level scope generated by the loop) scope.

So, the following code is finally implemented

<body> <ul> <li>1</li> <li>2</li> <li>3</li> </ul> <script> var lis=document.querySelectorAll('li') for(let i=0; i<lis.length; i++){ lis[i].onclick=function(){ lis[i].style.color='red' } } </script> </body>Copy the code

summary

  • The let keyword is used to declare variables
  • Variables declared using the let keyword have block-level scope
  • Variables declared in braces using the let keyword have block-level scope. The var keyword does not
  • Prevents loop variables from becoming global variables
  • Variables declared using the let keyword have no variable promotion
  • Variables declared using the let keyword have the temporary deadband property

2.2 const (★★★)

Declare a constant, which is the amount by which a value (memory address) cannot change

The value of a variable can change

let m=10
m=20
m='aa'
Copy the code

Once a constant is declared and assigned, its value cannot be changed

Constants are designed to prevent developers from accidentally changing certain fixed values, such as PI

Has block-level scope

 if (true) { 
     const a = 10;
 }
console.log(a) // a is not defined
Copy the code

What is the output of the following code?

 if (true) {
     const n = 10
     if (true) {
         const n = 20
         console.log(n)
     }
     console.log(n)
 }
 console.log(n)
Copy the code

Dry stove

  • Constants have block-level scope
  • The inner scope has access to constants from the outer scope, so if const n=20 is not declared, the inner scope prints 10
  • The outer scope has no access to constants in the inner scope, so the root of the outer scope is unaware that the constant n is declared in the inner scope

Constants must be assigned when they are declared

const PI; // Missing initializer in const declaration
Copy the code

After a constant is assigned, its value cannot be modified

const PI = 3.14;
PI = 100; // Assignment to constant variable.

const ary = [100.200];
ary[0] = 'a';
ary[1] = 'b';
console.log(ary); // ['a', 'b']; 
ary = ['a'.'b']; // Assignment to constant variable.
Copy the code

summary

  • The variable declared by const is a constant
  • Since it is a constant and cannot be reassigned, it cannot change the value if it is a basic data type or change the address value if it is a complex data type
  • Const must be declared with a given value

2.3 Differences between let, const and VAR

  • The variable declared with var is scoped in the function where the statement is located, and the variable is promoted
  • Variables declared using let are scoped within the block of code in which the statement resides, and there is no variable promotion
  • A const declaration is a constant, the value of which cannot be modified in subsequent code

2.4 Deconstructing Assignment (★★★)

The new syntax for destructuring assignments makes it easier to assign values to variables, but without it, it still doesn’t affect code

ES6 allows you to extract values from arrays, assign values to variables, and deconstruct objects

An array of deconstruction

When arrays are destructively assigned, declared variables are enclosed with []

 let [a, b, c] = [1.2.3];
 console.log(a)/ / 1
 console.log(b)/ / 2
 console.log(c)/ / 3
// If the deconstruction fails, the value of the variable is undefined
Copy the code

If there are more variables than there are elements in the array

Var arr = [' li ', 'du fu, bai juyi'] let [a, b, c, d] = arr console, log (a, b, c, d)Copy the code

The extra variable is undefined

Object to deconstruct

Object destructs the assignment, and the declared variables are enclosed with {}

 let person = { name: 'zhangsan'.age: 20 }; 
 let { name, age } = person;
 console.log(name); // 'zhangsan' 
 console.log(age); / / 20

 let {name: myName, age: myAge} = person; // myName myAge belongs to an alias
 console.log(myName); // 'zhangsan' 
 console.log(myAge); / / 20

Copy the code

Complex object deconstruction assignment

// let student = {name: 'zhang3 ', age: 18, address: {type:' zhang3 ', city: 'shijiazhuang'}} let {name: myname, age: myage, address: {province, city}} = student console. The log (myname myage, province, city)Copy the code

summary

  • Deconstructing assignment involves breaking up data structures and assigning values to variables
  • If the structure is unsuccessful and the variable does not match the number of values, the variable value is undefined
  • Array destructions are wrapped in brackets and multiple variables are separated by commas, and object destructions are wrapped in curly braces and multiple variables are separated by commas
  • Using deconstructed assignment makes it easy to fetch properties and methods from objects

2.5 Arrow Function (★★★)

The new way of defining functions in ES6 is intended to simplify function definition

() = > {}//() : represents a function; => : required symbol, which code block to point to; {} : function body
const fn = () = > {}// assigns a function to fn
Copy the code

There is only one line of code in the function body, and the result of the code execution is the return value. You can omit the curly braces

 function sum(num1, num2) { 
     return num1 + num2; 
 }
 / / es6 writing
 const sum = (num1, num2) = > num1 + num2; 

Copy the code

If the parameter has only one, you can omit the parentheses

 function fn (v) {
     return v;
 } 
/ / es6 writing
 const fn = v= > v;

Copy the code

Case Reference:

// Remove the function keyword, and do not need the function name, Var f = function () {console.log('f')} f() var f1 = () => {console.log('f1')} f1() // if the function has arguments function f2(m, n) { console.log(m + n) } f2(3, 4) var f3 = (m, n) => console.log(m + n) f3(4, Function f4(m) {console.log(m * 10)} f4(5) // var f5 = (m) => console.log(m * 10) Var f5 = m => console.log(m * 10) f5(10) function f6(m, n) {return (m + n)} console.log(f6(10, f6) {return (m + n)} console.log(f6(10, f6) 20)) // In the arrow function, if you want to return data, if it is 1 row, you can omit {}, You don't need to return the var f7 = (m, n) = > m + n console. The log (f7 (30, 40))/weight/function have more lines of code var arr = [1, 2, 3, 4, 5] function sum(number) { let sum = 0 number.forEach(function (item) { sum += item }) return sum } console.log(sum(arr))  var sum_arrow = numbers => { let sum = 0 numbers.forEach(item => { sum += item }) return sum } console.log(sum_arrow(arr))Copy the code

The arrow function is not bound to the this keyword. The this in the arrow function refers to the context this where the function is defined

const obj = { name: 'Joe'} 
 function fn () { 
     console.log(this);// This points to an obj object
     return () = > { 
         console.log(this);// This points to the position defined by the arrow function, so the arrow function is defined inside fn, and fn points to obj, so this also points to obj}}const resFn = fn.call(obj); 
 resFn();

Copy the code

I printed it twice above, both as obj objects

If you change the arrow function in the fn function to a normal function

summary

  • The arrow function does not bind this. The this in the arrow function points to the position it defines
  • The advantage of the arrow function is that it solves some of the problems caused by the this execution environment. For example, the problem of anonymous function this pointing to (anonymous function execution environment is global), including setTimeout and setInterval caused by the use of this

Classic Interview questions

var age = 100;

var obj = {
	age: 20.say: () = > {
		alert(this.age)
	}
}

obj.say();// The arrow function this points to the declared scope, while the object has no scope, so the arrow function is defined in the object, but this points to the global scope

Copy the code

2.6 Remaining Parameters (★★)

The residual argument syntax allows us to represent an indefinite number of arguments as an array. The undefined argument definition is a convenient way to declare a function without knowing the arguments

/* If the number of arguments in a function is not certain, use the rest of the argument. 3) The parameter type is not limited. 4) The parameter is stored as an array in the parameter */ // use arrow function rewrite // var fn = (... ary) => console.log(ary) function fn(... ary) { console.log(ary) } fn() fn(1) fn(1, 3) fn(33, 1, 44, 'a', false) fn('p', { name: 'yhb' }, [1, 2, 3])Copy the code

Residual parameters can also be used with normal parameters

Function ary_pad(ary,... ForEach (function (item) {ary. Push (item)})} //var ary_pad = (ary,... elements) => { // elements.forEach(item => ary.push(item)) //} let tmp = [] ary_pad(tmp, 1, 2, Three, four, five, 'a') to the console. The log (TMP)Copy the code

Sum case

const sum = (. args) = > {
    let total = 0
    args.forEach(item= > total += item)
    return total
}
console.log(sum(10.20.50))
Copy the code

The remaining parameters are used in conjunction with deconstruction

let students = ['wangwu'.'zhangsan'.'lisi'];
let [s1, ...s2] = students; 
console.log(s1);  // 'wangwu' 
console.log(s2);  // ['zhangsan', 'lisi']

Copy the code

3. Built-in object extensions for ES6

JS has a lot of built-in objects, such as Arra, Math, Date, String, etc. ES6 on the basis of the original, a few new methods

3.1 Array Extension Methods (★★)

Extension operators (expansion syntax)

The extension operator converts an array or object into a comma-separated sequence of arguments, acting opposite to the rest of the arguments

 let ary = [1.2.3]; . ary/ / 1, 2, 3
 console.log(... ary);// 1, 2, 3, equivalent to the following code
 console.log(1.2.3);
Copy the code

Ask? Why can’t I write it this way

let res=... aryCopy the code

Case study:

console.log(Math.max(4, 3, 11, 2, 66, 7)) let ary = [4, 3, 11, 2, 66, 7] console.log(Math.max(... Ary) console. The log (' -- -- -- -- -- -- -- -- -- -- -- -- ') var sum = (x, y) = > x + y console. The log (sum (4, 5)) console. The log (sum (... [5, 6] / / 5, 6))Copy the code
Extension operators can be applied to merge arrays
/ / method
 let ary1 = [1.2.3];
 let ary2 = [3.4.5];
 let ary3 = [...ary1, ...ary2];
 / / method 2ary1.push(... ary2);Copy the code
Convert a class array or traversable object into a true array

Type conversion array baidu many answers, here small series but more introduction

Case study:

/ / class array let divs = document. QuerySelectorAll (' div ') / / if there is no this line of code, Divs =[...divs] divs.push(2) console.log(divs) var ary =[1, 2, 3] ary.push(5) console.log(ary)Copy the code

Constructor method: array.from ()

The array. from method is used to convert two types of objects into true arrays: array-like objects and iterable objects (including the new ES6 data structures Set and Map).

What is an array-like object

Class arrays are collections of elements obtained using the querySelectorAll, getElementsByClassName, and other apis

/ * the lis is a class array object * / let lis = document. QuerySelectorAll (' li ') console. The log (lis) console. The log (lis) length) / / figure out whether the lis array Console. log(lis.__proto__) var arr = [1, 2, 3, 4] console.log(arr) console.log(arr.length) // Check whether arR is Array console.log(arr instanceof Array) //true // View object prototype of ARR console.log(arr.__proto__)Copy the code

Converts an array-like object to a bit array

From (lis) console.log(ary_lis instanceof Array) //trueCopy the code

And then there’s this literal object, which is also an array object

// Define a collection
let arrayLike = {
    '0': 'a'.'1': 'b'.'2': 'c'.length: 3
}; 
// convert to array
let arr2 = Array.from(arrayLike); // ['a', 'b', 'c']
Copy the code

The map method can also take a second argument, similar to the map method of arrays, that processes each element and puts the processed value into the returned array

  The /* length attribute determines how many attributes are converted to elements in the array. That is, the length attribute specifies the number of elements in the array. The array allocates space according to this value */
        let arrayLike = {
            "0": 1."1": 2."2": 3."3": "a"."4": false."length":3
        }
        let ary = Array.from(arrayLike, item= > {
            if(typeof item=='number') {return item
            }
        })
        console.log(ary)
Copy the code

Note: If it is an object, then the attribute needs to be indexed

Instance method: find()

Used to find the first eligible array member, returns undefined if none is found

let ary = [{
     id: 1.name: 'Joe'
 }, { 
     id: 2.name: 'bill'
 }]; 
 let target = ary.find((item, index) = > item.id == 2);// Select a value from the array where id = 2, note that only the first value is matched

Copy the code

Instance method: findIndex()

Used to find the location of the first eligible array member, or -1 if none is found

let ary = [1.5.10.15];
let index = ary.findIndex((value, index) = > value > 9); 
console.log(index); / / 2
Copy the code

Example method: includes()

Checks whether an array contains a given value, returning a Boolean value.

[1.2.3].includes(2) // true 
[1.2.3].includes(4) // false

Copy the code

3.2 Extension methods for String

Template String (★★★)

The new method of creating strings in ES6 is defined using backquotes

let name = `zhangsan`;

Copy the code
Variables can be parsed in template strings
let name = 'Joe'; 
let sayHello = `hello,my name is ${name}`; // hello, my name is zhangsan
Copy the code
Line breaks are possible in template strings
 let result = { 
     name: 'zhangsan'.age: 20.sex: 'male' 
 } 
 let html = ` <div>
     <span>${result.name}</span>
     <span>${result.age}</span>
     <span>${result.sex}</span>
 </div> `;

Copy the code
Functions can be called from within the template string
const sayHello = function () { 
    return 'Ha, ha, ha, ha, ha, ha. Can't catch me. I'm so strong.';
 }; 
 let greet = `${sayHello()}Hahaha ';
 console.log(greet); // Can't catch me, I am so strong, hahaha

Copy the code

Instance methods: startsWith() and endsWith()

  • StartsWith () : Indicates whether the argument string is at the head of the original string, returning a Boolean value
  • EndsWith () : Indicates whether the argument string is at the end of the original string, returning a Boolean value
let str = 'Hello world! ';
str.startsWith('Hello') // true 
str.endsWith('! ')       // true

Copy the code

Instance method: repeat()

The repeat method means that the original string is repeated n times, returning a new string

 console.log('x'.repeat(3));
Copy the code

3.3 Set Data Structure (★★)

Es6.ruanyifeng.com/#docs/set-m…

ES6 provides a new data structure, Set. It is similar to an array, but the values of the members are unique and there are no duplicate values.

The Set itself is a constructor used to generate the Set data structure

const s = new Set(a);Copy the code

Get familiar with the basic API of SET

// var arr=new Array() // Create an object of set type var s =new set () s.dd (1) s.dd (2) s.dd (2) // Cannot add duplicate members console.log(s) // Returns the number of members Console. log(s.size) // Delete member 2 s.delelete (2) console.log(s.size)Copy the code

The Set function can take an array as an argument to initialize.

const set = new Set([1.2.3.4.4]);/ / {1, 2, 3, 4}

Copy the code

You can also create an empty set and then add elements using the Add method

const s = new Set()
var ary=[2, 3, 5, 4, 5, 2, 2]
ary.forEach(item => s.add(item))
console.log(s)
Copy the code

Note: If you omit the ary variable above, you will get an error if you write it like this

 const s = new Set(a)// Do not omit the semicolon
 [2.3.5.4.5.2.2].forEach(item= > s.add(item))
 console.log(s)
Copy the code

Instance methods

  • Add (value) : Adds a value and returns the Set structure itself
  • Delete (value) : deletes a value and returns a Boolean value indicating whether the deletion is successful
  • Has (value) : Returns a Boolean value indicating whether the value is a member of Set
  • Clear () : Clears all members with no return value
 const s = new Set(a); s.add(1).add(2).add(3); // Add values to the set structure
 s.delete(2)             // Delete the 2 value from the set structure
 s.has(1)                // Returns a Boolean value indicating whether there is 1 in the set structure
 s.clear()               // Clear all values in the set structure
 // Note that the value of the element is deleted, not the index represented
Copy the code

traverse

An instance of a Set structure, like an array, has a forEach method that performs some operation on each member and returns no value.

s.forEach(value= > console.log(value))

Copy the code

Array merge to reorder case

Var array = [1, 2, 1, 1, '1', '1']; Var array1 = [1, '2', 2, 'a', 3, 4, '5', '1', '6']. // Create a set and place the elements in the array. Var s1=new Set(array) array1.forEach(item=>s1.add(item)) var newArr= array. from(s1) newarr.sort () console.log(newArr)Copy the code