当前位置:网站首页>Understand all the basic grammar of ES6 in one article
Understand all the basic grammar of ES6 in one article
2022-07-29 01:28:00 【Taro paste】
Introduction
What is? ES6 And why ES6?
ES The full name is ECMAScript , It is from ECMA International Organization for Standardization , A standardized specification for scripting languages .
ES6 Full name ECMAScript 6.0 , yes JavaScript The next version of the standard ,2015.06 release .
Every birth of standards means the perfection of language , Function enhancement .JavaScript There are also some unsatisfactory aspects of language itself .
- ES6 Mainly to solve ES5 The innate deficiency of , such as JavaScript There's no concept of class in it
- The variable promotion feature increases the unpredictability of program runtime
- The grammar is too loose , To achieve the same function , Different people may write different code
ES6 New syntax
let keyword (***)
ES6 For Declare variables Key words of
1. let The declared variable is only in the Block level validity
- Block level validity refer to for loop ,if Judgment statement, etc In braces {} Count as Block level scope
- let Only declared variables have block level scope ,var The declared variable has no block level scope
if (true) {
let a = 10;
}
console.log(a) // a is not defined
let stay if Variables declared in the statement , stay if You can't use it outside the statement
2. No variable promotion
Variables must be Declaration before use
console.log(a); // a is not defined
let a = 20;
Variable Promotion Variables can be used to define ;
3. Temporary dead zone
utilize let Declared variables will binding In this Block level scope , Will not be affected by the outside world
var tmp = 123;
if (true) {
let tmp = 'abc';
console.log(tmp); // Output abc
}
console.log(tmp); // Output 123
Summary
- let Keywords are used to declare variables
- Use let The variable declared by the keyword has a block level scope
- In a brace Use let Only variables declared by keyword have block level scope var Keywords don't have this feature
- Prevent loop variables from becoming global variables
- Use let The variable declared by the keyword has no variable promotion
- Use let The variable declared by the keyword has a temporary deadband property
const keyword (***)
declare constant , A constant is a value ( Memory address ) Can't change The amount of
1. Has block level scope
if (true) {
const a = 10;
}
console.log(a) // a is not defined
2. You must assign a value to a constant when you declare it
If the value is not assigned, an error will be reported
const PI; // Missing initializer in const declaration
3. Constant cannot be modified after assignment ( The memory address cannot be changed )
- The value of a simple data type cannot be changed
- Complex data type Inside Of Property value can change , But you can't assignment
const PI = 3.14;
PI = 100; // Assignment to constant variable. Report errors
const ary = [100, 200];
ary[0] = 'a';// You can change the attribute values in complex data types
ary[1] = 'b';
console.log(ary); // ['a', 'b'];
ary = ['a', 'b']; // Assignment to constant variable. to ary You can't assign values
Summary
- const The declared variable is a constant
- Since it is a constant, it cannot be assigned again , If basic data type , The value cannot be changed , If it's a complex data type , The address value cannot be changed
- Statement const You have to give a value when
let、const、var The difference between
- Use var Declared variables , Its scope is within the function of the statement , And there is the phenomenon of variable promotion >
- Use let Declared variables , Its scope is in the code block where the statement is located , No variable promotion
- Use const Declared constant , You can't change the value of this constant in later code
Deconstruct assignment (***)
An array of deconstruction
Allows you to extract values from an array , Assign a value to the variable according to the corresponding position
var arr = [1, 2, 3];
let [a, b, c,d] = arr ;
console.log(a)//1
console.log(b)//2
console.log(c)//3
console.log(d)//undefined
Be careful : If there are redundant values , Then the redundant value is undefined
Object to deconstruct
According to a certain pattern , Extract from object , Assign the extracted value to another variable
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 Belong to alias
console.log(myName); // 'zhangsan'
console.log(myAge); // 20
Summary
- Deconstruction assignment is to decompose the data structure , Then assign values to the variables - If the structure is not successful , When the number of variables does not match the number of values , The value of the variable is undefined - Array deconstruction is wrapped in brackets , Multiple variables are separated by commas , Object deconstruction is wrapped in curly braces , Multiple variables are separated by commas - The use of deconstruction assignment can make it convenient for us to get the properties and methods in the object
Arrow function (***)
The arrow function is ES6 New ways to define functions .
() => {} //(): Represents a function ;
- =>: Must have symbols , Which code block to point to ;
- {}: The body of the function
- const fn = () => {}// To assign a function to fn
1. There is only one code in the function body , And the code execution result is the return value , You can omit the braces
function sum(num1, num2) {
return num1 + num2;
}
//es6 How to write it
const sum = (num1, num2) => num1 + num2;
If there is only one parameter , You can omit parentheses
function fn (v) {
return v;
}
//es6 How to write it
const fn = v => v;
Arrow functions are not bound this keyword , In the arrow function this, It points to the context where the function is defined this
const obj = {
name: ' Zhang San '}
function fn () {
console.log(this);//this Point to yes obj object
return () => {
console.log(this);//this Point to Is the position defined by the arrow function , So this arrow function is defined in fn Inside , And this fn Point to yes obj object , So this this It also points to obj object
}
}
const resFn = fn.call(obj);
resFn();
Summary
- There is no binding in the arrow function this, In the arrow function this Pointing is the position it defines , It can be simply understood as , Defining the scope of an arrow function this Point to the who , Who it points to - The advantage of the arrow function is that it solves this Some of the problems caused by the execution environment . such as : Solved anonymous function this Pointed question ( The execution environment of anonymous functions is global ), Include setTimeout and setInterval Use in this The problems caused
The remaining parameters (**)
The residual parameter syntax allows us to An indefinite number of parameters To express as a Array , How to define indefinite parameters ,
This way is very convenient 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)
The remaining parameters are used in conjunction with the deconstruction
let students = ['wangwu', 'zhangsan', 'lisi'];
let [s1, ...s2] = students;
console.log(s1); // 'wangwu'
console.log(s2); // ['zhangsan', 'lisi']
ES6 Built in object extensions for
Array Extension method of (**)
Extension operator ( Expand grammar )
The extension operator can put Array perhaps object Conversion to use Comma separated parameter sequence
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);
1. Extension operators can be applied to merge arrays
// Method 1
let ary1 = [1, 2, 3];
let ary2 = [3, 4, 5];
let ary3 = [...ary1, ...ary2];
// Method 2
ary1.push(...ary2);
2. Convert an array of classes or traversable objects into a real array
let oDivs = document.getElementsByTagName('div');
oDivs = [...oDivs];
Array Example method
Constructor method :Array.from()
1. Convert a pseudo array or traversable object to a real array
// Define a set
let arrayLike = {
'0': 'a',
'1': 'b',
'2': 'c',
length: 3
};
// Turn it into an array
let arr2 = Array.from(arrayLike); // ['a', 'b', 'c']
2. Method can also accept the second parameter , Act like an array map Method , Used to process each element , Put 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]
Be careful : If it's an object , Then the attribute needs to write the corresponding index
Example method :find()
Used to find out first Eligible array members , If no return is found undefined
let ary = [{
id: 1,
name: ' Zhang San '
}, {
id: 2,
name: ' Li Si '
}];
let target = ary.find((item, index) => item.id == 2);// Find the values that match the conditions in the array , When an element in an array id be equal to 2 Find out , Be careful , It will only match the first
Example method :findIndex()
Used to find out first The position of the eligible array members , If no return is found -1
let ary = [1, 5, 10, 15];
let index = ary.findIndex((value, index) => value > 9);
console.log(index); // 2
Example method :includes()
Determine whether an array contains a given value , Returns a Boolean value .
[1, 2, 3].includes(2) // true
[1, 2, 3].includes(4) // false
String Extension method of
Template string (***)
ES6 New ways to create strings , Use Backquote definition
let name =
zhangsan;
1. Variables can be parsed in the template string
let name = ' Zhang San ';
let sayHello = `hello,my name is ${
name}`; // hello, my name is zhangsan
2. The template string can wrap
let result = {
name: 'zhangsan',
age: 20,
sex: ' male '
}
let html = ` <div> <span>${
result.name}</span> <span>${
result.age}</span> <span>${
result.sex}</span> </div> `;
3. The function can be called in the template string
const sayHello = function () {
return ' Ha ha ha ha Can't catch me I'm just so powerful ';
};
let greet = `${
sayHello()} Ha ha ha ha `;
console.log(greet); // Ha ha ha ha Can't catch me I'm just so powerful Ha ha ha ha
Example method :startsWith() and endsWith()
- startsWith(): Indicates whether the parameter string is in the header of the original string , Returns a Boolean value
- endsWith(): Indicates whether the parameter string is at the end of the original string , Returns a Boolean value
et str = 'Hello world!';
str.startsWith('Hello') // true
str.endsWith('!') // true
Example method :repeat()
repeat Method to repeat the original string n Time , Returns a new string
'x'.repeat(3) // "xxx"
'hello'.repeat(2) // "hellohello"
Set data structure (**)
ES6 Provides a new data structure Set. It's like an array , But the value of members is Unique , There are no duplicate values .
- Set Itself a constructor , Used to generate Set data structure
const s = new Set();
- Set Function can take an array as an argument , Used to initialize .
const set = new Set([1, 2, 3, 4, 4]);//{1, 2, 3, 4}
Example method
- dd(value): Add a value , return Set Structure itself
- delete(value): Delete a value , Returns a Boolean value , Indicates whether the deletion is successful
- has(value): Returns a Boolean value , Indicates whether the value is Set Members of
- clear(): Clear all members , no return value
const s = new Set();
s.add(1).add(2).add(3); // towards set Add value to structure
s.delete(2) // Delete set The structure of the 2 value
s.has(1) // Express set Whether there is... In the structure 1 This value Returns a Boolean value
s.clear() // eliminate set All values in the structure
// Be careful : What is deleted is the value of the element , It's not a representative index
Traverse
Set An instance of a structure is the same as an array , Also have forEach Method , Used to perform some kind of operation on each member , no return value .
s.forEach(value => console.log(value))
Good luck is hidden in effort ~

边栏推荐
- 时间复杂度、空间复杂度的学习总结
- Prometheus 的 API 稳定性保障
- The solution to keep the height of the container unchanged during the scaling process of the uniapp movable view table
- Canal real-time parsing MySQL binlog data practice
- mysql 创建索引的三种方式
- Docuware mobile labor solution can help you build a new productivity model: anytime, anywhere, any device
- 【idea】查询字段使用位置
- ActiveMQ basic details
- APP接入Kakaotalk三方登录
- 云原生应用综合练习下
猜你喜欢

Groundwater, soil, geology and environment

redis安装,集群部署与常见调优

Expression evaluation

【idea】查询字段使用位置

瑞吉外卖项目实战Day01

Self-attention neural architecture search for semantic image segmentation

云原生应用综合练习下

Intel introduces you to visual recognition -- openvino

PlatoFarm社区生态福音,用户可借助Elephant Swap获得溢价收益

C语言300行代码实现扫雷(可展开+可标记+可更改困难级别)
随机推荐
Third party login process of flask Weibo
PlatoFarm社区生态福音,用户可借助Elephant Swap获得溢价收益
js判断 数组/对象数组 1 是否包含数组/对象数组 2
Flask reports an error: pymysq1.err OperationalError:(1054, “Unknown column ‘None‘ in ‘field list‘“)
MySQL time is formatted by hour_ MySQL time format, MySQL statement queried by time period [easy to understand]
Canal real-time parsing MySQL binlog data practice
Linux Redis 源码安装
Digital currency of quantitative transactions - generate foot print factor data
Subtotal of process thread coordination
【Leetcode-滑动窗口问题】
Summary of process and thread knowledge points 2
Error reporting: SQL syntax error in flask. Fields in SQL statements need quotation marks when formatting
瑞吉外卖项目实战Day01
PLATO上线LAAS协议Elephant Swap,用户可借此获得溢价收益
uniapp movable-view表格缩放过程想保持容器高度不变的解决办法
跨模态对齐 20220728
什么是原码、反码和补码
regular expression
App access kakaotalk three party login
(perfect solution) why is the effect of using train mode on the train/val/test dataset good, but it is all very poor in Eval mode