ES6 Syntax
target
- Ability to say the characteristics of using let keywords to declare variables
- Ability to extract values from arrays using deconstruction assignments
- Ability to say what an arrow function has
- Ability to receive remaining function parameters using remaining parameters
- Ability to split groups using extended operators
- Ability to say what attributes a template string has
Concepts related to ES6 ()
What is ES6
The full name of ES is ECMAScript, which is a standardized specification for scripting languages developed by the ECMA International Organization for Standardization.
[External chain picture transfer failed, source station may have anti-theft chain mechanism, it is recommended to save the picture and upload it directly (img-NBvDwTg5-1591928104162)(images/es-version.png)]
Why use ES6?
The birth of each standard means the improvement of language and the enhancement of function.There are also some unsatisfactory aspects to the JavaScript language itself.
- Variable promotion increases the unpredictability of program runtime
- The syntax is too loose to do the same thing, different people may write different code
ES6 New Syntax
let(★★★)
A new keyword for declaring variables was added in ES6
let-declared variables are valid only at the block level
if (true) { let a = 10; } console.log(a) // a is not defined
**Note: ** Variables declared with let keyword have block-level scope, while variables declared with var do not have block-level scope characteristics.
No Variable Promotion
console.log(a); // a is not defined let a = 20;
Transient Dead Zone
Variables declared with let are bound to this block-level scope and are not affected by the outside world
var tmp = 123; if (true) { tmp = 'abc'; let tmp; }
Classic interview questions
var arr = []; for (var i = 0; i < 2; i++) { arr[i] = function () { console.log(i); } } arr[0](); arr[1]();
[External chain picture transfer failed, source station may have anti-theft chain mechanism, it is recommended to save the picture and upload it directly (img-9CWN8k22-1591928104166)(images/let interview question.png)]
**Classic Interview Question illustration:**The key point of this question is that the variable i is global and the output of the function is global i value.
let arr = []; for (let i = 0; i < 2; i++) { arr[i] = function () { console.log(i); } } arr[0](); arr[1]();
[External chain picture transfer failed, source station may have anti-theft chain mechanism, it is recommended to save the picture and upload it directly (img-6LccXuJJ-1591928104168)(images/let interview question 2.png)]
**Classic Interview Question illustration:**The key point of this question is that each loop produces a block-level scope, each variable in the block-level scope is different, and the function executes with the output of the i value in the scope of its parent (the block-level scope generated by the loop).
Summary
- The let keyword is used to declare variables
- Variables declared with let keywords have block-level scope
- Variables declared in a brace using the let keyword do not have this feature unless they have a block-level scope var keyword
- Prevent loop variables from becoming global
- Variables declared with let keyword have no variable promotion
- Variables declared with the let keyword have a temporary dead zone property
const(★★★)
Declare a constant, which is a variable whose value (memory address) cannot be changed
Has Block Scope
if (true) { const a = 10; } console.log(a) // a is not defined
A constant must be assigned when it is declared
const PI; // Missing initializer in const declaration
After a constant is assigned, the 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.
Summary
- A variable declared by const is a constant
- Since constants cannot be reassigned, values cannot be changed if they are basic data types, and address values cannot be changed if they are complex data types
- const must be declared with a given value
Differences between let, const, var
- Variables declared with var are scoped within the function in which the statement resides and are subject to variable promotion
- A variable declared with let whose domain is within the block of code in which the statement resides does not have a variable promotion
- Constant is declared and its value cannot be modified in subsequent code
[External chain picture transfer failed, source station may have anti-theft chain mechanism, it is recommended to save the picture and upload it directly (img-4aN51bR7-1591928104170) (images/var&let&const difference.png)]
Deconstruction assignment
ES6 allows you to extract values from arrays, assign values to variables by location, and deconstruct objects
Array Deconstruction
let [a, b, c] = [1, 2, 3]; console.log(a)//1 console.log(b)//2 console.log(c)//3 //If the deconstruction is unsuccessful, the value of the variable is undefined
Object Deconstruction
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 is an alias console.log(myName); // 'zhangsan' console.log(myAge); // 20
Summary
- Deconstruction assignment is to decompose the data structure and assign values to variables
- If the structure is unsuccessful and the number of values does not match, the value of the variable is undefined
- Array deconstruction is wrapped in square brackets, multiple variables are separated by commas, object deconstruction is wrapped in curly brackets, and multiple variables are separated by commas
- Using deconstruction assignment allows us to easily retrieve attributes and methods from objects
Arrow Function ()
New way to define functions in ES6.
() => {} //(): Represents a function; =>: the necessary symbol, which block of code to point to; {}: body of function const fn = () => {}//Represents assigning a function to fn
There is only one sentence of code in the body of the function, and the result of executing the code is the return value, which can be omitted from braces
function sum(num1, num2) { return num1 + num2; } //es6 Writing const sum = (num1, num2) => num1 + num2;
If there is only one parameter, parentheses can be omitted
function fn (v) { return v; } //es6 Writing const fn = v => v;
The arrow function does not bind the this keyword, this in the arrow function points to the context where the function is defined
const obj = { name: 'Zhang San'} function fn () { console.log(this);//this points to an obj object return () => { console.log(this);//This is where the arrow function is defined, so this arrow function is defined in fn, and this FN is pointing to the obj object, so this is also pointing to the obj object } } const resFn = fn.call(obj); resFn();
Summary
- This is not bound in an arrow function. The this in an arrow function points to the position it defines. It can be simply understood that the this that defines the scope in an arrow function points to whomever it points to.
- The advantage of the arrow function is that it solves some problems caused by this execution environment.For example, the problem pointed to by anonymous function this has been solved (the execution environment of anonymous function is global), including the problem caused by using this in setTimeout and setInterval
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 although the arrow function is defined in the object, this points to the global scope
Remaining parameters ()
The Remaining Parameter syntax allows us to express an indefinite number of parameters as an array in a convenient way to declare a function without knowing the parameters
function sum (first, ...args) { console.log(first); // 10 console.log(args); // [20, 30] } sum(10, 20, 30)
Use of remaining parameters with deconstruction
let students = ['wangwu', 'zhangsan', 'lisi']; let [s1, ...s2] = students; console.log(s1); // 'wangwu' console.log(s2); // ['zhangsan', 'lisi']
Built-in Object Extensions for ES6
Array's Extension Method ()
Extension Operator (Expansion Syntax)
Extension operators convert arrays or objects to comma-separated parameter sequences
let ary = [1, 2, 3]; ...ary // 1, 2, 3 console.log(...ary); // 1 2 3, equivalent to the code below console.log(1,2,3);
Extension operators can be applied to merged arrays
// Method One let ary1 = [1, 2, 3]; let ary2 = [3, 4, 5]; let ary3 = [...ary1, ...ary2]; // Method 2 ary1.push(...ary2);
Converts an array of classes or traversable objects to a real array
let oDivs = document.getElementsByTagName('div'); oDivs = [...oDivs];
Constructor method:Array.from()
Converts a pseudo array or traversable object to a real array
//Define a set let arrayLike = { '0': 'a', '1': 'b', '2': 'c', length: 3 }; //Convert to Array let arr2 = Array.from(arrayLike); // ['a', 'b', 'c']
The method also accepts the second parameter, acting like an array map method, which processes each element and places the processed value into the returned array
let arrayLike = { "0": 1, "1": 2, "length": 2 } let newAry = Array.from(arrayLike, item => item *2)//[2,4]
Note: If it is an object, then the attribute needs to be indexed accordingly
Instance method: find()
Used to find the first eligible array member, if no undefined return is found
let ary = [{ id: 1, name: 'Zhang San' }, { id: 2, name: 'Li Si' }]; let target = ary.find((item, index) => item.id == 2);//Find the qualified values in the array, and when the element id in the array equals 2, note that only the first one will be matched
Instance method: findIndex()
Used to find the position of the first eligible array member, if no Return-1 is found
let ary = [1, 5, 10, 15]; let index = ary.findIndex((value, index) => value > 9); console.log(index); // 2
Instance method: include ()
Returns a Boolean value by determining whether an array contains a given value.
[1, 2, 3].includes(2) // true [1, 2, 3].includes(4) // false
String's Extension Method
Template string ()
ES6's new way of creating strings, defined with inverted Quotes
let name = `zhangsan`;
Variables can be parsed in Template Strings
let name = 'Zhang San'; let sayHello = `hello,my name is ${name}`; // hello, my name is zhangsan
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> `;
Functions can be called in the template string
const sayHello = function () { return 'Hahaha can't catch up with me, I'm just so strong'; }; let greet = `${sayHello()} Ha ha ha ha`; console.log(greet); // Hahaha can't catch up with me, I'm just so strong.
Instance methods: startsWith() and endsWith()
- startsWith(): Returns a Boolean value indicating whether the parameter string is at the head of the original string
- endsWith(): Returns a Boolean value indicating whether the parameter string is at the end of the original string
let str = 'Hello world!'; str.startsWith('Hello') // true str.endsWith('!') // true
Instance method: repeat()
The repeat method means to repeat the original string n times and return a new string
'x'.repeat(3) // "xxx" 'hello'.repeat(2) // "hellohello"
Set Data Structure
ES6 provides a new data structure Set.It is similar to an array, but members have unique values and no duplicate values.
Set itself is a constructor for generating Set data structures
const s = new Set();
The Set function can accept an array as an argument to initialize.
const set = new Set([1, 2, 3, 4, 4]);//{1, 2, 3, 4}
Instance Method
- add(value): Add a value and return the Set structure itself
- delete(value): Deletes a value and returns a Boolean value indicating whether the deletion was successful
- has(value): Returns a Boolean value indicating whether the value is a member of the Set
- clear(): Clear all members, no return value
const s = new Set(); s.add(1).add(2).add(3); // Add value to set structure s.delete(2) // Delete 2 values from set structure s.has(1) // Indicates whether 1 in the set structure returns a Boolean value s.clear() // Clear all values in the set structure //Note: Delete the value of the element, not the index it represents
ergodic
Instances of the Set structure, like arrays, have a forEach method that performs an action on each member with no return value.
s.forEach(value => console.log(value))