let
- You can define variables inside a block with the new keyword let
- Variables defined by the LET can be accessed within the block-level scope
Block-level scope
Scope – The scope within which a member can act
- Global scope
- Function scope
- Block-level scope
A block is a range wrapped around {}
// Great for setting loop variables in for loops
// Let defines variables that are valid only in its own loop
for (let i = 0 ; i < 3 ; i++) {
for (let i = 0; i < 3; i++) {console.log(i); }}// Add events in batches through a loop
// Variables defined by let can only be called inside the block level
var eles = [{}, {}, {}];
for (let i = 0 ; i < eles.length ; i++) {
eles[i].onclick = function () {
console.log(i);
}
}
eles[0].onclick();
// The loop actually has two scopes
for (let i = 0 ; i < 10 ; i++) {
let i = "foo";
console.log(i);
}
let i = 0;
if (i < 10) {
let i = "foo";
console.log(i);
}
i++;
// Differs from var in that let does not promote variable declarations
console.log(a);
let a = 2;
Copy the code
const
Constant/constant adds a read-only effect to let
// Cannot change the value
const name = "zs";
name = "ls";
// The declaration must be accompanied by an initial value
const name;
name = "zs";
// Attributes can be added to the object type
const obj = {};
obj.name = "zs";
Copy the code
Best practice: Use const instead of var, with let
Array deconstruction
// Deconstruct the value of the corresponding subscript
const arr = [100.200.300];
const [foo, bar, baz] = arr;
console.log(foo, bar, baz);
/ / 100 200 300
// Deconstruct only the values of the required subscripts
const arr = [100.200.300];
const [, , baz] = arr;
console.log( baz);
/ / 300
// Deconstruct all values from the beginning to the end of the current subscript
const arr = [100.200.300];
const [foo, ...rest] = arr;
console.log(rest);
/ / [200300]
// The deconstructed item is smaller than the array length
const arr = [100.200.300];
const [foo] = arr;
console.log(foo);
/ / 100
// The deconstructed item is larger than the array length
// Default values can be assigned when destructing
const arr = [100.200.300];
const [foo, bar, baz = 400, more = 123] = arr;
console.log(more);/ / 123
console.log(baz);/ / 300
// Real application
const path = "foo/bar/baz";
// const temp = path.split("/");
// const a = temp[1];
const [,,a] = path.split("/");
console.log(a);
Copy the code
Object deconstruction
// We need to extract the content based on the attribute name
const obj = { name: 'zs'.age: 18 };
const { name } = obj;
console.log(name);
// If the variable name is the same, add a new name after the colon
// The default value can also be assigned with an equal sign
const name = "tom";
const { name: newName = "jack" } = obj;
console.log(name);//tom
console.log(newName);//zs
Copy the code
Template string literal
// Wrap string content with ' '
const str = `this is a \`string`;
console.log(str);
// You can wrap variables inside strings with ${}
const name = "tom";
const str = `hey, ${name}.The ${1 + 1}.The ${Math.random()}`;
console.log(str);
Copy the code
Template string tag function
const name = "zs";
const gender = true;
// Use strings to accept pure characters
//strings[0] hi,
//strings[1] is a
function myTagFunc(strings, name, gender) {
const sex = gender ? "man" : "woman";
return strings[0] + name + strings[1] + sex + strings[2];
}
const str = myTagFunc`hi, ${name} is a ${gender}`;
console.log(str);
//hi, zs is a man
Copy the code
String extension methods
const msg = 'Error: foo is not defined.'
// Whether to start with a string
console.log(msg.startsWith('Error'))
// Whether to end with a string
console.log(msg.endsWith('. '))
// Whether to contain a string
console.log(msg.includes('foo'))
Copy the code
Parameter Default Value
// Default values for function arguments
function foo(bar,enable = true) {
// enable = enable || true
// enable = enable === undefined ? true : enable
console.log('foo invoked enable:')
console.log(enable)
}
foo('bar')
Copy the code
The remaining parameters
// Remaining parameters
function fun(n,... args) {
console.log(args);
/ / / 2 and 4
}
fun(1.2.3.4);
Copy the code
An array of
// Expand the array operation
const arr = ['foo'.'bar'.'baz']
// console.log(arr[0],arr[1],arr[2])
// console.log.apply(console,arr)
console.log(... arr)Copy the code
Arrow function
// Simplify the syntax of functions
const plus = (a, b) = > {
console.log('plus invoked')
return a + b
}
console.log(plus(1.2))
// Real application
// Returns an odd number of items in an array
const arr = [1.2.3.4.5.6.7]
// const arr1 = arr.filter(function (item) {
// return item % 2
// })
const arr1 = arr.filter(i= > i % 2)
console.log(arr1)
Copy the code
Arrow function and this
// The arrow function does not have this inside, it looks around
const person = {
name: "tom".// Can not get name
sayHi: () = > {
console.log(`hi,my name is The ${this.name}`)}sayHiWait: function () {
setTimeout(() = > {
SayHi's this will be found
console.log(`hi,my name is The ${this.name}`)},1000);
}
}
person.sayHi()
Copy the code
Object literals are enhanced
const bar = "bar"
const age = "age"
const obj = {
name: "tom".// Omit the variable name if the attribute name is the same as the variable name
bar,
// Simplifies function syntax
sayHi () {
console.log('hi')
console.log(this)},// Property names can be dynamically computed
[1+2] :18
}
console.log(obj)
Copy the code
Object extension method
Object. The assign method
Copies properties from multiple source objects into one target object
const source1 = {
a: 123.b: 123
}
const source2 = {
b: 678.d: 789
}
const target = {
a:456.c:789
}
const result = Object.assign(target,source1,source2);
console.log(target)
//a: 123 b: 678 c: 789 d: 789
// Copy objects
function fun(obj) {
// If you want internal changes, do not change external objects
const newObj = Object.assign({},obj)
newObj.name = 'tom'
console.log(newObj)
}
const obj = {
name: 'jack'.age: 18
}
fun(obj)
console.log(obj)
// apply, simplify when receiving options object parameters
function Block(options) {
Object.assign(this,options)
}
const block1 = new Block({width: 100.height: 100.x: 50.y: 50})
console.log(block1)
Copy the code
The Object is method
Used to handle some special comparison cases
0= =false // true
0= = =false // false
+0= = = -0 // true
NaN= = =NaN //false
Object.is(+0, -0) // false
Object.is(NaN.NaN) // true
Copy the code
Class Class
A new way to define objects
// The old way of writing
// function Person(name, age) {
// this.name = name;
// this.age = age;
// }
// Person.prototype.sayHi = function () {
// console.log(`hi,my name is ${this.name}`)
// }
class Person {
constructor (name, age) {
this.name = name;
this.age = age;
}
sayHi () {
console.log(`hi,my name is The ${this.name}`)}}const p1 = new Person("tom".18)
console.log(p1)
p1.sayHi()
Copy the code
A static method
Also called class method, this refers to the current class
class Person {
constructor (name, age) {
this.name = name;
this.age = age;
}
sayHi () {
console.log(`hi,my name is The ${this.name}`)}static create (name,age) {
return new Person(name,age)
}
}
// Call class methods to create instance objects directly
const p1 = Person.create("zs".19)
console.log(p1)
Copy the code
Extends
/ / parent class
class Person {
constructor (name, age) {
this.name = name;
this.age = age;
}
sayHi () {
console.log(`hi,my name is The ${this.name}`)}}/ / subclass
class Student extends Person {
constructor (name,age,number) {
// Call the parent constructor
super(name,age)
this.number = number
}
hello () {
// Call the superclass function
super.sayHi()
console.log(` student number isThe ${this.number}`)}}const s1 = new Student("tom".18.101)
s1.hello();
Copy the code
Set data structure
No duplicate values are allowed in this data structure
// Create a data structure
const s0 = new Set()
s.add(1).add(2).add(3).add(4).add(2)
console.log(s)
/ / traverse
s.forEach(i= > console.log(i))
for (let i of s) {
console.log(i)
}
// Get the length of the set
console.log(s.size)
// Whether a value exists
console.log(s.has(4))
// Delete a value
console.log(s.delete(100))
// Clear the collection
s.clear()
// Actually apply array de-duplication
const arr = [1.3.4.6.2.4.7.5.8]
// const b = Array.from(new Set(arr))
// Returns an array using the expansion operator
const b = [...new Set(arr)]
console.log(b)
Copy the code
Map data structure
Any type can be set to a key value
const map = new Map(a)const a = { a: 1}
map.set(a,100)
// Get the corresponding value
console.log(map.get(a))
// map.has() contains some data
/ / a map. The delete () to delete
/ / a map. The clear () to empty
/ / traverse
map.forEach((value,key) = > {
console.log(key,value)
})
Copy the code
Symbol
A new primitive data type is used to represent a unique value
const s = Symbol(a)console.log(s)
console.log(typeof s)
// You can add a description text
console.log(Symbol('foo'))
// Symbol as attribute name cannot be accessed externally
const obj = {
[Symbol()] : 789.name: "zs"
}
obj[Symbol= ()]123
obj[Symbol= ()]456
console.log(obj[Symbol()])
console.log(obj.name)
Copy the code
For method
To reuse a value of type symbol, use the for method
const a = Symbol.for(true)
const b = Symbol.for('true')
console.log(a === b)
Copy the code
toStringTag
Use symbol’s toStringTag constant to modify the label of the converted object as a string
const obj = {
[Symbol.toStringTag]: "XObject"
}
console.log(obj.toString())
Copy the code
for… Of circulation
As a unified way to traverse all data structures
// go through the number group
const arr = [100.200.300.400]
for (const item of arr) {
console.log(item)
}
// Iterate over the set object
const s = new Set(["foo"."bar"."baz"])
for (const item of s) {
console.log(item)
}
// Traverses the map object
const m = new Map()
m.set("foo".1)
m.set("bar".2)
for (const [key,value] of m) {
console.log(key,value)
}
Copy the code
ES2016
The includes method of the array
Checks whether a value is included
const arr = [1.true.NaN.23.'hello']
console.log(arr.indexOf(NaN))// Cannot find the location of NaN
console.log(arr.includes(NaN))/ / returns true
Copy the code
The exponential operator **
/ / the console log (math.h pow (2, 3))
console.log(2六四屠杀3)
Copy the code