ES6 basic grammar - study notes

First, what is ES6

ES stands for ECMAScript, it is by ECMA International Organization for Standardization, the development of standardized specifications a scripting language. ES6 is actually a general reference, refers to the ES2015 and subsequent versions.

Pros:
Variable upgrade feature adds unpredictability program runs
grammar too loose, to achieve the same functionality, different people might write different code.

Two, ES6 the new syntax

2.1 let
the ES6 new keywords used to declare variables.

  • There is no variable lift
 console.log(a); // a is not defined 
  let a = 20
  • Temporary dead zone
    using the keyword to declare a variable let's have block-level scope, can prevent the loop variable becomes a global variable.
if (true) {
			let num = 10;
			console.log(num);   //10
			
		}
           console.log(num);  //not defined

2.2const
action: declare a constant, constant is the value (memory address) the amount can not be changed.

  • Having a block-level scope
if (true) {
 const a = 10; }
console.log(a) // a is not defined
  • When the assignment must declare constants
const PI;    // Missing initializer in const declaration
  • After constant values, the values ​​can not 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.

The difference between 2.3 let, const, var of

where let const
Function-level scope Block-level scope Block-level scope
Variable lift There is no variable lift There is no variable lift
You can change the value You can change the value Unchangeable

2.4 destructuring assignment
ES6 allowed values extracted from the array, in a corresponding position on the variable. Objects can also be achieved deconstruction.

  • An array of deconstruction
// 数组解构允许我们按照一一对应的关系从数组中提取值 然后将值赋值给变量
	//如果解构不成功,变量的值为undefined。
	let [a, b, c, d, e] =[1,2,3];
	console.log(a)  //1
	console.log(b)  //2
	console.log(c)  //3
	console.log(d) //undefined
	console.log(e) //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 属于别名
console.log(myName); // 'zhangsan' 
console.log(myAge); // 20

2.5 Functions arrow
embodiment ES6 the new function is defined.

  • grammar
(参数) => {函数体} 
const fn = () => {}

//函数体中只有一句代码,且代码的执行结果就是返回值,可以省略大括号
function sum(num1, num2) {
 return num1 + num2; }
const sum = (num1, num2) => num1 + num2;
//如果形参只有一个,可以省略小括号
function fn (v) {
	  return v; 
 }
const fn = v => v;
  • Arrow function does not bind this keyword, the function of this arrow, points to the position defined in the context of this function.

		var age = 100;

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

		obj.say();   //alter的是100

2.6 remaining parameters
remaining parameters and with the use of deconstruction

let students = ['wangwu', 'zhangsan', 'lisi'];
//...s2将剩余的实参归成一个数组
let [s1, ...s2] = students;
console.log(s1); // 'wangwu' 
console.log(s2); // ['zhangsan', 'lisi']

With the remaining sum function parameter write

const sum = (...args) => {
			let total = 0;
			args.forEach(item => total += item);
			return total;
		};

		console.log(sum(10, 20)); //30
		console.log(sum(10, 20, 30));//60
		

Three, ES6 expansion of built-in objects

  • Extension method (1) Array of

3.1.1 Extended operator (developing syntax)
extended operator array can be split into a sequence of parameters in a comma-separated.


	   // 扩展运算符可以将数组拆分成以逗号分隔的参数序列
		// ...ary 等于 "a", "b", "c"
		let ary = ["a", "b", "c"];
		console.log(...ary)        //a b c
		console.log("a", "b", "c")  //a b c

      //扩展运算符应用于数组合并
		 let ary1 = [1, 2, 3];
		let ary2 = [4, 5, 6];
		let ary3 = [...ary1, ...ary2];
		console.log(ary3)  //[1,2,3,4,5,6]
		ary1.push(...ary2); // 合并数组的第二种方法
		console.log(ary1) //[1,2,3,4,5,6]

    // 利用扩展运算符将伪数组转换为真正的数组
		var oDivs = document.getElementsByTagName('div');
		 var ary = [...oDivs];		

3.1.2 constructor method: Array.from ()
converts the array or traverse the object class for the real array.

var arrayLike = {
			"0": "1",
			"1": "2",
			"length": 2
		}
		//将类数组或可遍历对象转换为真正的数组
		var ary = Array.from(arrayLike);
	   console.log(ary)  //["1", "2"]
	   
	   //方法还可以接受第二个参数,用来对每个元素进行处理,将处理后的值放入返回的数组。
		var ary = Array.from(arrayLike, item => item * 2)
		console.log(ary)  //[2, 4]

3.1.3 instance method: find ()
to find the first qualifying array members, if not found returns undefined

var ary = [{
			id: 1,
			name: '张三'
		}, {
			id: 2,
			name: '李四'
		}];
		let target1 = ary.find((item, index) => item.id == 2);
		console.log(target1);  //Object id: 2 name: "李四"
		let target2 = ary.find(item => item.id == 3);
		console.log(target2);//undefined

3.1.4 instance method: findIndex ()
to find the first member of the array in line with the conditions of the location, or -1 if not found

let ary = [1, 5, 10, 15];
let index1 = ary.findIndex((value, index) => value > 9);
let index2 = ary.findIndex((value, index) => value > 20);
console.log(index1); // 2
console.log(index2); // -1

3.1.55 Example Method: includes ()
indicates whether the array contains a given value, returns a Boolean value.

	let ary = ["a", "b", "c"];
		let result1 = ary.includes('a')  
		let result2 = ary.includes('e')
		console.log(result1) //true	
		console.log(result2) //false
  • (2) String extension method

3.2.1 template string
new ES6 create a string of way, use of anti-quoted definition.

//用反引号定义
let name = `zhangsan`;

Advantages:
template string variables can be resolved.
Template string can wrap
can call a function in the template string.

//模板字符串中可以解析变量
let name = `张三`;
		let sayHello = `Hello, 我的名字叫${name}`;
		console.log(sayHello);   //Hello, 我的名字叫张三
		
//在模板字符串中可以调用函数
	const fn = () => {
			return '我是fn函数'
		}

		let h = `我是模板字符串 ${fn()}`;
		console.log(h);  //我是模板字符串 我是fn函数

		
//模板字符串中可以换行
let html = `
			<div>
				<span>${name}</span>
			</div>
		`;
		console.log(html);
		//输出:  <div>
		//		    <span>张三</span>
		//	   </div>

The method of Example 3.2.2: startsWith () and endsWith ()
startsWith (): whether the parameter string representing the head of the string, returns a boolean
endsWith (): Indicates whether the parameter string at the end of the string, returns a Boolean value

let str = 'Hello world!';
str.startsWith('Hello') // true 
str.endsWith('!') // true

The method of Example 3.2.3: REPEAT ()
REPEAT method represents the original string is repeated n times, returns a new string.

	console.log("y".repeat(5))  //yyyyy
  • (3) Set the data structure
    ES6 provides new data structure Set. It is similar to an array, but the value of the member is unique, no duplicate values.
    Syntax 3.3.1
    Set itself is a constructor to generate Set data structure.
    Set function can accept an array as a parameter to initialize.
const s = new Set();
const set = new Set([1, 2, 3, 4, 4]);

3.3.2 instance method
add (value): add some value, return Set structure itself
delete (value): delete a value, returns a Boolean value that indicates whether the deletion success
has (value): Returns a Boolean value that indicates the Set value is a member of the
clear (): remove all members, no return value


const s = new Set();
s.add(1).add(2).add(3); // 向 set 结构中添加值
s.delete(2) // 删除 set 结构中的2值 s.has(1) // 表示 set 结构中是否有1这个值 返回布尔值
s.clear() // 清除 set 结构中的所有值

3.3.3 traversing
Examples Set structures and arrays, also has forEach method for performing a certain operation on each member, there is no return value.

	// 遍历set数据结构 从中取值
		const s = new Set(['a', 'b']);
		s.forEach(value => {
			console.log(value)    //a b
		})

Published 21 original articles · won praise 3 · Views 326

Guess you like

Origin blog.csdn.net/weixin_43482965/article/details/104707291