ES6特性

Posted by Chenyawei on 2020-07-24
Words 2k and Reading Time 9 Minutes
Viewed Times

一、let和const

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
//var声明的变量往往会越域
//let声明的变量严格局部作用域
// {
// var a = 1;
// let b = 2;
// }
// console.log(a);
// console.log(b); //1-let.html:17 Uncaught ReferenceError: b is not defined

//var 可以多次声明
//let 只能声明一次
// var m = 3;
// var m = 4;
// let n = 5;
// let n = 6;
// console.log(m);
// console.log(n); //Uncaught SyntaxError: Identifier 'n' has already been declared

//var 会变量提升
//let 不会变量提升
// console.log(x); // undefined
// var x = 10;
// console.log(y); // Uncaught ReferenceError: Cannot access 'y' before initialization
// let y = 20;

// 一旦声明必须初始化, 只读变量
const c = 4;
c = 5; //Uncaught TypeError: Assignment to constant variable.
console.log(c);

二、解构表达式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
let arr = [1,2,3];
a = arr[0];
b = arr[1];
c = arr[2];
console.log("a="+a,"b="+b,"c="+c);
//解构表达式
let[x,y,z] = arr;
console.log(x,y,z);


const person = {
name: "jack1",
age: 18,
language: ['java','css','js']
}
const name = person.name;
const age = person.age;
const language = person.language;
console.log(name,age,language);
//对象解构
const {name:abc,age,language} = person;
console.log(abc,age,language);

//字符串扩展
let str = "hello str";
console.log(str.startsWith("hello"));
console.log(str.endsWith("str"));
console.log(str.includes("s"));
console.log(str.includes("str"));

function fun(){
return "这是一个函数!";
}
//字符串扩展
let htm = `
<div>
<span>我是${abc},年龄${age + 10}; I want say : ${fun()}</span>
</div>
`;

console.log(htm);

三、函数优化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
// ES6以前给我们给一个函数的参数设置默认值,只能采用变通的写法
function add(a,b){
// b如果为空设置为1
b = b || 1;
return a + b;
}
console.log(add(10));

// 现在可以直接写上默认值,没有传就直接使用默认值
function add2(a, b=1){
return a + b;
}
console.log(add2(20));

// 不定参数
function fun(...values){
console.log(values);
}
fun(1,2);
fun(1,2,3,4);

// 箭头函数
//以前声明一个函数
function print(obj){
console.log(obj);
}

// var print = obj => console.log(obj);
// print("hello");

// var sum2 = (a,b) => a + b;
// console.log(sum2(1,2));

// var sum3 = (a,b) => {
// c = a+b;
// console.log(a+c);
// }
// console.log(sum3(1,2));

let person={
name: "jack",
age: 13,
language: ['java','css','js']
}

function hello(param){
console.log("hello " + param.name);
}
hello(person);

// 解构函数
var hello2 = ({name}) => console.log("hello " + name);
hello2(person);

四、对象优化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
const person = {
name: "lucy",
age: 99,
language:['java','css','js']
}

console.log(Object.keys(person)); // ["name", "age", "language"]
console.log(Object.values(person)); // ["lucy", 99, Array(3)]
console.log(Object.entries(person)); // [Array(2), Array(2), Array(2)]

// 对象合并
const target = {a: 1};
const source1 = {b: 2};
const source2 = {c: 3};
Object.assign(target,source1,source2); //source1和source2合并到 target
console.log(target); // {a: 1, b: 2, c: 3}

//声明对象简写
const age = 12;
const name = "zhangsan";
const person1 = {age: age, name: name}; //传统写法
console.log(person1);
const person2 = {age,name}; // 属性名和属性值的变量名都一样时,可以缩写
console.log(person2);

//对象的函数属性简写
let person3 = {
name: "jack",
//以前
eat: function (food) {
console.log(this.name + "在吃" + food);
},
//箭头函数,this不能使用,必须使用对象属性
eat2: food => console.log(person3.name + "在吃" + food),
eat3(food){
console.log(person3.name + "在吃" + food);
}
}
person3.eat("🍎");
person3.eat2("🍌");
person3.eat3("🍊");

// 对象扩展运算符
//1 拷贝(深拷贝)
let p1 = {name: "lucy", age: 8};
let someone = {...p1};
console.log(someone);

//2 和并对象
let age1 = {age: 9};
let name1 = {name: "xiaoming"};
let p2 = {...age1,...name1};
console.log(p2);

五、map和reduce方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
//数组中新增了map和reduce方法
//map(): 接收一个函数,将原数组中的所有元素用这个函数处理后放入新数组返回。
let arr = ['1','20','40','-5'];
arr = arr.map((item)=>{
return item*2;
});
arr = arr.map(item=>item*2);

console.log(arr);
//reduce() 为数组中的每一个元素依次执行回调函数,不包含数组中被删除或从未被赋值的元素,
//arr.reduce(callback,[initalValue])
/**
1, previousValue (上一次调用回调返回的值,或者是提供的初始值(initialValue))
2, currentValue (数组中当前被处理的元素)
3,index (当前元素在数组中的索引)
4,array (调用reduce的数组)
*/
let result = arr.reduce((a,b)=>{
console.log("上一次处理后:" + a);
console.log("当前正在处理:" + b);
return a + b;
},100);
console.log(result);

六、Promise 对象

Promise 在JavasCript的世界中,所有代码都是单线程执行的。由于这个“缺陷”,导致JavasCript的所有网络操作,浏览器事件,都必须是异步执行。异步执行可以用回调函数实现。一旦有一连串的ajax请求啊a, b , c , d … 后面的请求依赖前面的请求结果,就需要层层嵌套。这种缩进和层层嵌套的方式,非常容易造成上下文代码混乱,我们不得不非常小心翼翼处理内层函数与外层函数的数据,一旦内层函数使用了上层函数的变量,这种混乱程度就会加剧……总之,这种’层叠上下文’的层层嵌套方式,着实增加了神经的紧张程度。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
案例:用户登录,并展示该用户的各科成绩。在页面发送两次请求: 
1 .查询用户,查询成功说明可以登录
2 .查询用户成功,查询科目
3 .根据科目的查询结果,获取去成绩
分析:此时后台应该提供三个接口,一个提供用户查询接口,一个提供科目的接口,一个提供各科成绩的接口,为了渲染方便,最好响应跳现数据。在这里就不编写后台接口了,而是提供三个json文件,直接提供json数据,模拟后台接口:

user.json
{
"id": 1,
"name": "jack",
"password":"123123"
}

user_corse_1.json
{
"id": 10,
"name": "English"
}

corse_score_10.json
{
"id": 100,
"score": 99
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
//1 ajax嵌套查询
//查询当前用户信息
//根据当前用户id查询课程信息
//根据课程信息id查询分数
$.ajax({
url: "./mock/user.json",
success(data){
console.log("查询的用户:" , data);
$.ajax({
url: `./mock/user_corse_${data.id}.json`,
success(data){
console.log("查询的课程:" , data);
$.ajax({
url: `./mock/corse_score_${data.id}.json`,
success(data){
console.log("查询的分数:" , data.score);
},
error(err){
console.log("查询异常:",err);
}
});
}
});
},
error(err){
console.log("查询异常:",err);
}
});

//2 promise 封装异步操作
let p = new Promise((resolve,reject)=>{
$.ajax({
url: "./mock/user.json",
success(data){
console.log("查询用户信息:", data);
resolve(data);
},
error(err){
reject(err);
}
});
});
p.then((obj)=>{
return new Promise((resolve,reject)=>{
$.ajax({
url: `./mock/user_corse_${obj.id}.json`,
success(data){
console.log("查询课程信息:", data);
resolve(data);
},
error(err){
reject(err);
}
});
});
}).then((obj)=>{
$.ajax({
url: `./mock/corse_score_${obj.id}.json`,
success(data){
console.log("查询分数:", data);
},
error(err){
console.log("查询异常:",err);
}
});
}).catch((err)=>{
console.log("查询异常:",err);
});

// 3 封装公共方法
function get(url,data){
return new Promise((resolve,reject)=>{
$.ajax({
url: url,
data: data,
success(data){
resolve(data);
},
error(err){
reject(err);
}
})
});
}

get("./mock/user.json")
.then((data)=>{
console.log("查询用户信息成功:",data);
return get(`./mock/user_corse_${data.id}.json`);
})
.then((data)=>{
console.log("查询课程信息成功:", data);
return get(`./mock/corse_score_${data.id}.json`);
})
.then((data)=>{
console.log("查询分数为:", data);
}).catch(err=>{
console.log("查询异常:",err);
});

七、模块化

模块化就是把代码进行拆分,方便重复利用。类似java中的导包,要使用一个包,必须先导包。而JS中没有包的概念,换来的是模块

模块功能主要由两个命令构成:export 和 import

  • export 命令用于规定模块的对外接口。
  • import命令用于导入其它模块提供的功能。

user.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const name = "jack";
const age = 40;

function add(a,b){
return a + b;
}

//导出default ,import时可以自定义变量名xxx: import xxx from "user.js"
export default{
mul(a,b){
return a*b;
}
}

export {name,age,add};

utils.js

1
2
3
4
5
6
7
let util ={
sum(a,b){
return a + b;
}
}

export {util};

main.js

1
2
3
4
import util from "./utils.js"
import {name,age,add} from "./user.js"

console.log(util.sum(3,4),name,age);

notice

欢迎访问 chenyawei 的博客, 若有问题或者有好的建议欢迎留言,笔者看到之后会及时回复。 评论点赞需要github账号登录,如果没有账号的话请点击 github 注册, 谢谢 !

If you like this blog or find it useful for you, you are welcome to comment on it. You are also welcome to share this blog, so that more people can participate in it. If the images used in the blog infringe your copyright, please contact the author to delete them. Thank you !