【前端】ES6

ES6

ECMAScript6.0(以下简称ES6,ECMAScript是一种由Ecma国际通过ECMA-262标准化的脚本),是JavaScript语言的下一代标准,2015年6月正式发布,从ES6开始的版本号采用年号,如ES2015,就是ES6。ES2016就是ES7。ECMAScript 是规范,JS 是规范的具体实现。

ES6 是 JavaScript 语言的下一代标准,2015年6月正式发布。它的目标,是使得JavaScript语言可以用来编写复杂的大型应用程序,成为企业级开发语言。

let && const

  • var 在 {} 之外也起作用,let 在 {} 之外不起作用
  • var 多次声明同一变量不会报错,let 多次声明会报错,只能声明一次。
  • var 会变量提升(打印和定义可以顺序反),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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>


<script>
// var 声明的变量往往会越域
// let 声明的变量有严格局部作用域
// {
// var a = 1;
// let b = 2;
// }
// console.log(a); // 1
// console.log(b); // ReferenceError: b is not defined

// var 可以声明多次
// let 只能声明一次
// var m = 1
// var m = 2
// let n = 3
// let n = 4
// console.log(m) // 2
// console.log(n) // Identifier 'n' has already been declared

// var 会变量提升
// let 不存在变量提升
// console.log(x); // undefined
// var x = 10;
// console.log(y); //ReferenceError: y is not defined
// let y = 20;

// const
// 1. const声明之后不允许改变
// 2. 一但声明必须初始化,否则会报错
const a = 1;
a = 3; //Uncaught TypeError: Assignment to constant variable.

</script>

</body>
</html>

模板字符串

使用 `` 将字符串包裹起来。

  1. 第一个用途:基本的字符串格式化。将表达式嵌入字符串中进行拼接。用 ${} 来界定。
1
2
3
4
5
// es5    
let name = 'itcast'
console.log('hello ' + name) //es6
const name = 'itcast'
console.log(`hello ${name}`) //hello itcast
  1. 第二个用途:在ES5时我们通过反斜杠()来做多行字符串或者字符串一行行拼接。ES6反引号(``)直接搞定。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>模板字符串</title>
</head>
<body>
<script>
var username = "张三";
var age = 30;
// 1: 原始的做法就是去拼接字符串
var str = "我名字叫 " + username+",年龄是: "+age;
console.log(str);
// 2:用模板字符串来拯救 注意:这里是 `(飘键) (tab键盘的上面那个键)
// jdk1.9
var str2 = `我名字叫 ${username},年龄是: ${age}`;
console.log(str2);
</script>
</body>
</html>

解构表达式

  • 支持 let arr = [1,2,3]; let [a,b,c] = arr; 这种语法
  • 支持对象解析:const { name: abc, age, language } = 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
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<script>
//数组解构
// let arr = [1,2,3];
// // let a = arr[0];
// // let b = arr[1];
// // let c = arr[2];

// let [a,b,c] = arr;
// console.log(a,b,c)

const person = {
name: "jack",
age: 21,
language: ['java', 'js', 'css']
}
// const name = person.name;
// const age = person.age;
// const language = person.language;

//对象解构
const { name: abc, age, language } = person;
console.log(abc, age, language)

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

//字符串模板
let ss = `<div>
<span>hello world<span>
</div>`;
console.log(ss);

// 字符串插入变量和表达式。变量名写在 ${} 中,${} 中可以放入 JavaScript 表达式。

function fun() {
return "这是一个函数"
}

let info = `我是${abc},今年${age + 10}了, 我想说: ${fun()}`;
console.log(info);

// 对象解构 --- es6提供一些获取快捷获取对象属性和行为方式
var person = {
name:'zhangsan',
age:32,
language:"cn",
// 函数也有处理
/* say:function(){
console.log(this.name+"年龄是:" + this.age);
} */
/* say:()=>{
console.log(this.name+"年龄是:" + this.age);
} */
say(){
console.log(this.name+"年龄是:" + this.age);
}
};
// ===========================传统的做法========================
var name = person.name;
var age = person.age;
person.say();
// ===========================对象解构做法========================
//es6的做法 前提:默认情况name,age必须是jsonkey.
var {name,age} = person;
console.log(name,age);
// 可以用冒号取小名
var {name,age,language:lan} = person;
console.log(name,age,lan);
</script>
</body>
</html>

函数优化

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
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<script>
//在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.length)
}
fun(1, 2) //2
fun(1, 2, 3, 4) //4

// 箭头函数
// 以前声明一个方法
// var print = function (obj) {
// console.log(obj);
// }
var print = obj => console.log(obj);
print("hello");

var sum = function (a, b) {
c = a + b;
return a + c;
}

var sum2 = (a, b) => a + b;
console.log(sum2(11, 12));

var sum3 = (a, b) => {
c = a + b;
return a + c;
}
console.log(sum3(10, 20))


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

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

var sum = (a = 100,b = 300)=>{
console.log(a+b);
};

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

</script>
</body>
</html>

箭头函数

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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>箭头函数</title>
</head>
<body>
<script>
// 箭头函数
// 它也是一种函数的定义,它简化定义仅此而已。
// 步骤:1:去掉function 2: 括号后面加箭头。
// 无参数的函数
//var sum = function(){
//}
// 箭头改造如下
//var sum = ()=>{}
// 有参数
// 第一种情况 一个参数的如下
//var sum2 = function(a){
//};
// 箭头改造如下
var sum2 = (a)=>{};
var sum2 = a=>{
return a;
};
// 第二种情况 二个参数的以上,记住括号一定要加
//var sum3 = function(a,b){
// return a + b;
//};
// 箭头改造如下
var sum3 = (a,b)=>{
return a + b;
};
// 第三种情况,如果没有逻辑体,只有返回值可以简化如下
//var sum4 = function(a,b){
// return a + b;
//};
// 箭头改造如下
var sum4 = (a,b)=>a+b
// 执行
console.log(sum2(100));
console.log(sum3(100,100));
console.log(sum4(100,100));
</script>
</body>
</html>

对象初始化简写

如果一个对象中的key和value的名字一样的情况下可以定义成一个。

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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<script>
const person = {
name: "jack",
age: 21,
language: ['java', 'js', 'css']
}

console.log(Object.keys(person));//["name", "age", "language"]
console.log(Object.values(person));//["jack", 21, 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 };

//{a:1,b:2,c:3}
Object.assign(target, source1, source2);

console.log(target);//["name", "age", "language"]

// 声明对象简写
const age = 23
const name = "张三"
const person1 = { age: age, name: name }

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(this.name + "在吃" + food);
}
}

person3.eat("香蕉");
person3.eat2("苹果")
person3.eat3("橘子");

// 对象拓展运算符

// 拷贝对象(深拷贝)
let p1 = { name: "Amy", age: 15 }
let someone = { ...p1 }
console.log(someone) //{name: "Amy", age: 15}

// 合并对象
let age1 = { age: 15 }
let name1 = { name: "Amy" }
let p2 = {name:"zhangsan"}
p2 = { ...age1, ...name1 }
console.log(p2)
</script>
</body>
</html>
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>对象简写</title>
</head>
<body>
<script>
function person(name, age) {
//return {name:name,age:age};
// 对象简写
return { name, age };
};
// 调用和执行
var json = person("小花花美美", 20);
console.log(json.name, json.age);
//========================= 实战应用 =========================
//<button onclick="login()">登录</button>
function login() {
var username = $("#username").val();
var password = $("#password").val();
// 发送ajax
$.ajax({
type: "post",
// 对象简写
data: { username, password },
// 原始写分
//data:{username:username,password:password},
success() {
}
});
}
</script>
</body>
</html>

传播操作符【…】

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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>ES6的语法:传播操作符【...】</title>
</head>
<body>
<script>
// 1: 定义一个对象
var person1 = {
name: '小飞飞',
age: 16,
};
// 2: 对象解构
var {name,age} = person1;
// =========================== ... 对象融合=====================
var person2 = {
...person1,
gender:1,
tel:13478900
};
console.log(person2);
// =========================== ... 对象取值=====================
// ... 对象取值
var person3 = {
name:"李四",
gender:1,
tel:"11111",
address:'广州'
};
// ...person4 把剩下没取走给我。
var {name,gender,...person4} = person3;
console.log(name)
console.log(age)
console.log(person4)
// =================场景分析 -----伪代码========================
// 模拟后台:异步查询返回用户数据 如下:
function findUsers(){
$.get("xxxxx",function(res){
var res = {
pages:11,
pageSize:10,
pageNo:1,
firstFlag:true,
lastFlag:false,
total:123,
data:[{},{},{},{}],
};
// ==========================对象 ... 取值===============
var {data:users,...pagesjon} = res;
//等价于
/* var users = res.data;
var pagesjon = {
res = {
pages:11,
pageSize:10,
pageNo:1,
firstFlag:true,
lastFlag:false,
total:123,
}; */
})
}
</script>
</body>
</html>

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
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>

<script>
//数组中新增了map和reduce方法。
//map():接收一个函数,将原数组中的所有元素用这个函数处理后放入新数组返回。
let arr = ['1', '20', '-5', '3'];

// arr = arr.map((item)=>{
// return item*2
// });
arr = arr.map(item=> item*2);

console.log(arr);
//reduce() 为数组中的每一个元素依次执行回调函数,不包括数组中被删除或从未被赋值的元素,
//[2, 40, -10, 6]
//arr.reduce(callback,[initialValue])
/**
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)


</script>
</body>
</html>

promise

以前嵌套 Ajax 的时候很繁琐。 解决方案:

把 Ajax 封装到 Promise 中,赋值给let p

  • 在 Ajax 中成功使用resolve(data),交给 then 处理,
  • 失败使用reject(err),交给catch处理 p.then().catch()
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<script>
//1、查出当前用户信息
//2、按照当前用户的id查出他的课程
//3、按照当前课程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);
// },
// error(error) {
// console.log("出现异常了:" + error);
// }
// });
// },
// error(error) {
// console.log("出现异常了:" + error);
// }
// });
// },
// error(error) {
// console.log("出现异常了:" + error);
// }
// });


//1、Promise可以封装异步操作
// let p = new Promise((resolve, reject) => { //传入成功解析,失败拒绝
// //1、异步操作
// $.ajax({
// url: "mock/user.json",
// success: function (data) {
// console.log("查询用户成功:", data)
// resolve(data);
// },
// error: function (err) {
// reject(err);
// }
// });
// });

// p.then((obj) => { //成功以后做什么
// return new Promise((resolve, reject) => {
// $.ajax({
// url: `mock/user_corse_${obj.id}.json`,
// success: function (data) {
// console.log("查询用户课程成功:", data)
// resolve(data);
// },
// error: function (err) {
// reject(err)
// }
// });
// })
// }).then((data) => { //成功以后干什么
// console.log("上一步的结果", data)
// $.ajax({
// url: `mock/corse_score_${data.id}.json`,
// success: function (data) {
// console.log("查询课程得分成功:", data)
// },
// error: function (err) {
// }
// });
// })

function get(url, data) { //自己定义一个方法整合一下
return new Promise((resolve, reject) => {
$.ajax({
url: url,
data: data,
success: function (data) {
resolve(data);
},
error: function (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)=>{ //失败的话catch
console.log("出现异常",err)
});

</script>
</body>

</html>

模块化

模块化就是把代码进行拆分,方便重复利用。类似于java中的导包, 而JS换了个概念,是导模块。

ES6 的模块化无法在 Node.js 中执行,需要用 Babel 编辑成 ES5 后再执行。

模块功能主要有两个命令构成 exportimport

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

user.js:

1
2
3
4
5
6
7
var name = "jack"
var age = 21
function add(a,b){
return a + b;
}

export {name,age,add}

hello.js:

1
2
3
4
5
6
7
8
9
10
11
12
13
// export const util = {
// sum(a, b) {
// return a + b;
// }
// }

export default {
sum(a, b) {
return a + b;
}
}
// export {util}
// export不仅可以导出对象,一切JS变量都可以导出。比如:基本类型变量、函数、数组、对象。

main.js:

1
2
3
4
5
6
import abc from "./hello.js"
import {name,add} from "./user.js"

abc.sum(1,2);
console.log(name);
add(1,3);