Let and const commands
There is no variable promotion in LET
The var command will cause “variable promotion”, that is, the variable can be used before the declaration, the value of undefined. The let command changes the syntactic behavior
// var case console.log(foo); Var foo = 2; //letThe situation of the console. The log (bar); / / error ReferenceErrorlet bar = 2;
Copy the code
Lets form block-level scopes
Block-level scopes are generally thought of as blocks wrapped in {}. Variables only work in this block
{
leta = 1; } console.log(a); // a is not definedCopy the code
The advent of block-level scopes has virtually eliminated the need for the widely used immediate-execution function expressions (IIFE). Here’s an interview question
var funcs = []
for (var i = 0; i < 10; i++) {
funcs.push(function() { console.log(i) })
}
funcs.forEach(function(func) {
func()
})
Copy the code
This is a very common interview question, a lot of students will see 10 times 10 but what if we want to output 0 through 9?
Const funcs = [] const funcs = []for (let i = 0; i < 10; i++) {
funcs.push(function() {
console.log(i)
})
}
funcs.forEach(function(func) {
func()
})
Copy the code
Achieve the same effect, ES6 simple solution is not more let you move!!
Temporary dead zone
As long as the let command exists in the block-level scope, the variable declared by it is “binding” to the region and is not affected by external influences. The variable is not available within the code block until it is declared by the let command. This is grammatically known as a “temporary dead zone” or TDZ
if (true) {// TDZ start TMP ='abc'; // ReferenceError
console.log(tmp); // ReferenceError
lettmp; // TDZ end console.log(TMP); // undefined tmp = 123; console.log(tmp); / / 123}Copy the code
Duplicate declarations are not allowed
Let does not allow the same variable to be declared twice in the same scope
/ / an errorfunction func() {
leta = 10; var a = 1; } / / an errorfunction func() {
let a = 10;
let a = 1;
}
Copy the code
Basic usage of const
Const declares a read-only constant. Once declared, the value of a constant cannot be changed,
Const PI = 3.1415; PI = 3; // TypeError: Assignment to constant variable.Copy the code
We usually declare let for variables and const for constants. Const is scoped in the same way as let: it is valid only in the block-level scope in which it is declared. Constants declared by const are also unpromoted and have a temporary dead band and can only be used after the declared position.
Nature of const
What const actually guarantees is not that the value of the variable cannot be changed, but that the data stored at the memory address to which the variable points cannot be changed.
const a = [];
a.push('Hello'); // 可执行
a.length = 0; // 可执行
a = ['Dave']; / / an errorCopy the code
In the code above, the constant A stores an address that points to an array. The only thing that’s immutable is the address, that is, you can’t point a to another address, but the array itself is mutable, and if you assign another array to A, you get an error.
2. Deconstruction assignment of variables
Destruct assignment of arrays
Essentially, this is “pattern matching,” in which the variable on the left is assigned a corresponding value as long as the pattern on both sides of the equal sign is the same
let [foo, [[bar], baz]] = [1, [[2], 3]];
foo // 1
bar // 2
baz // 3
let [ , , third] = ["foo"."bar"."baz"];
third // "baz"
let [x, , y] = [1, 2, 3];
x // 1
y // 3
Copy the code
Destruct assignment allows you to specify default values.
let [x, y = 'b'] = ['a']; // x='a', y='b'
Copy the code
If the deconstruction fails, the value of the variable is equal to undefined.
let [foo] = [];
let [bar, foo] = [1];
Copy the code
Object destructuring assignment
Deconstruction can be applied to objects as well as arrays.
let { foo, bar } = { foo: "aaa", bar: "bbb" };
foo // "aaa"
bar // "bbb"
Copy the code
Destruct assignment of a string
Strings can also deconstruct assignments. This is because at this point, the string is converted to an array-like object.
const [a, b, c, d, e] = 'hello';
a // "h"
b // "e"
c // "l"
d // "l"
e // "o"
Copy the code
Deconstruct the purpose of assignment
(1) Exchange the values of variables
let x = 1;
let y = 2;
[x, y] = [y, x];
Copy the code
(2) Return multiple values from the function
// Return an arrayfunction example() {
return [1, 2, 3];
}
let[a, b, c] = example(); // Return an objectfunction example() {
return {
foo: 1,
bar: 2
};
}
let { foo, bar } = example();
Copy the code
Template string
Template strings are handy to use and are often used to output a result. For example
var name = "Small strong"
console.log("My name is."+name) // Template string expression console.log(' My name is${name}`)
Copy the code
Arrow function
ES6 allows functions to be defined using arrows (=>)
var f = function (v) {
returnv*v; }; Var f = (v)=>{returnv*v; } // If your function has only one argument, you can omit the parentheses. You can omit {} and when a function returns only one expressionreturn
var f = v => v*v;
Copy the code
5. Array extensions
Extended operator
The spread operator (spread) is three points (…) . It is like the inverse of the REST argument, turning an array into a comma-separated sequence of arguments.
console.log(... [1, 2, 3]) // 1 2 3 console.log(1, ... [2, 3, 4], 5) // 1 2 3 4 5Copy the code
Extend the application of operators
(1) Copy an array (note: using the extension operator to copy an array is a deep copy. Two arrays are independent of each other. Changing the value of one does not affect the value of the other)
const a1 = [1, 2]; // const a2 = [...a1]; // const [...a2] = a1;Copy the code
(2) Merge arrays
const arr1 = ['a'.'b'];
const arr2 = ['c'];
const arr3 = ['d'.'e']; // ES5 merge array arr1.concat(arr2, arr3); / / /'a'.'b'.'c'.'d'.'e'[...arr1,...arr2,...arr3] // ['a'.'b'.'c'.'d'.'e' ]
Copy the code
(3) Combine with deconstruction assignment
const [first, ...rest] = [1, 2, 3, 4, 5];
first // 1
rest // [2, 3, 4, 5]
const [first, ...rest] = ["foo"];
first // "foo"
rest // []
Copy the code
(4) Extension operators can also turn strings into true arrays
[...'hello'] / ["h"."e"."l"."l"."o" ]
Copy the code
Array.from()
The array. from method is used to convert two types of objects into true arrays: array-like objects and iterable objects
let arrayLike = {
'0': 'a'.'1': 'b'.'2': 'c', length: 3 }; Var arr1 = [].slice.call(arrayLike); / / /'a'.'b'.'c'] // ES6letarr2 = Array.from(arrayLike); / / /'a'.'b'.'c']
Copy the code
It is worth noting that the extension operator (…) You can also turn some data structures into arrays.
Array.of()
The array. of method converts a set of values to an Array.
Array of (3, 11, 8) / /,11,8 [3] Array of (3) / / [3] Array) of (3). The length / / 1Copy the code
The main purpose of this method is to complement the Array constructor Array(). Array() behaves differently because of the number of arguments.
Find () and findIndex() of array instances
The find method of an array instance, used to find the first array member that matches the criteria. Its argument is a callback function that is executed by all array members until the first member that returns true is found, and then returned. If there is no qualified member, undefined is returned.
[1, 4, -5, 10].find((n) => n < 0)
// -5
Copy the code
The findIndex method on an array instance is used much like the find method, returning the location of the first qualified array member, or -1 if all members fail.
[1, 5, 10, 15].findIndex(function(value, index, arr) {
returnvalue > 9; / / 2})Copy the code
Fill () for array instances
The fill method fills an array with the given value.
['a'.'b'.'c'].fill(7)
// [7, 7, 7]
new Array(3).fill(7)
// [7, 7, 7]
Copy the code
The fill method can also accept a second and third parameters that specify where the fill starts and ends
['a'.'b'.'c'].fill(7, 1, 2)
// ['a'7,'c']
Copy the code
The code above shows that the fill method starts at bit 1, fills the original array with 7, and ends just before bit 2.
Includes () of array instances
The array.prototype. includes method returns a Boolean value indicating whether an Array contains a given value, similar to the includes method of strings.
[1, 2, 3].includes(2) // true
[1, 2, 3].includes(4) // false
[1, 2, NaN].includes(NaN) // true
Copy the code
Six, class
The class to create a class
(1) Class is the keyword, followed by the class name, the first letter of the class, adopt the big camel name principle. The class name is followed by {}.
(2) in {}, can not directly write statements, can only write methods, methods do not need to use the keyword
(3) There are no commas between methods. Not key-value pairs
Here’s an example:
class NBAPlayer{
constructor(name,age,height){
this.name = name
this.age = age
this.height = height
}
say() {the console. The log (` I am${this.name}This year, I${this.age}My height${this.height}`)
}
}
var rs = new NBAPlayer("Yao"."35"."226")
rs.say()
Copy the code
Use extends for inheritance
Note: In the constructor of a subclass, you must explicitly call the super method of the superclass; if not, this is not available
class NBAPlayer{
constructor(name,age,height){
this.name = name
this.age = age
this.height = height
}
say() {the console. The log (` I am${this.name}This year, I${this.age}My height${this.height}`)
}
}
class MVP extends NBAPlayer{
constructor(name,age,height,year){
super(name,age,height)
this.year = year
}
sayi() {the console. The log (` I am${this.name}, I am in${this.year}}} var rs = new MVP("Yao"."35"."226"."2014")
rs.say()
rs.sayi()
Copy the code
7. Set and map
(1) set
A set is a collection, just like an array, except that its values are unique and not duplicated. The Set itself is a constructor used to generate the Set data structure.
const s = new Set();
[2, 3, 5, 4, 5, 2, 2].forEach(x => s.add(x));
for (let i of s) {
console.log(i);
}
// 2 3 5 4
Copy the code
The code above adds members to the Set structure using the add method, which shows that the Set structure does not add duplicate values. For of
// Remove duplicate members from array [...new Set(array)]Copy the code
(2) the map
It is similar to an object in that it contains key-value pairs, except that the key names in an object can only be strings. In the case of a map, the keys can be arbitrary values.
const m = new Map();
const o = {p: 'Hello World'};
m.set(o, 'content')
m.get(o) // "content"
m.has(o) // true
m.delete(o) // true
m.has(o) // false
Copy the code
The above code uses the set method of the Map structure to treat the object O as a key of M, then reads the key using the get method, and then deletes the key using the DELETE method
const map = new Map([
['name'.'Joe'],
['title'.'Author']]); map.size // 2 map.has('name') / /true
map.get('name') / /"Zhang"
map.has('title') / /true
map.get('title') / /"Author"
Copy the code
As a constructor, a Map can also take an array as an argument. The members of this array are arrays representing key-value pairs.
Eight, strict mode
JS syntax is very flexible, and this flexible feature in JS does more harm than good. Later strict mode was added. The purpose of using strict mode: rules to improve compilation efficiency.
How to start Strict mode: “Use Strict”
What is the difference between strict mode and non-strict mode?
1. Do not use variables without var in strict mode
2. Numbers that cannot be in base 8 in strict mode
3. In strict mode, functions cannot be defined in if statements
4. Functions cannot have identical parameters in strict mode
5. Arguments cannot be used if they cannot be used in strict mode
6. In strict mode, this in function is no longer a window
Beginner ES6, the article is wrong please give directions, the text part of the inaccurate wording also please understand