首页 > 代码库 > es2015(es6)基础部分学习笔记(更新中...)

es2015(es6)基础部分学习笔记(更新中...)

1.let

 let可以声明块级作用域变量

1 ‘use strict‘;
2 
3 if (true) {
4     let app = ‘apple‘;
5 }
6 
7 console.log(app);  //外面是访问不到app的

 

2.const

 const可以声明常量

1 ‘use strict‘;
2 
3 const app = ‘apple‘;
4 console.log(app);
5 
6 const app = ‘peach‘;
7 console.log(app);  //报错,常量不能多次赋值

 

3.Destructuring 解构

 解构赋值允许使用类似数组或对象字面量的语法将数组和对象的属性赋给各种变量。

‘use strict‘;

function breakfast () {
    return [‘egg‘,‘bread‘,‘milk‘];
}

//传统方法
var arr = breakfast(), egg = arr[0], bread = arr[1], milk = arr[2];
console.log(egg,bread,milk);

//es6
let [t1,t2,t3] = breakfast();
console.log(t1,t2,t3);

 

4.对象解构

‘use strict‘;

function breakfast () {
    return {egg:‘egg‘, milk:‘milk‘, bread:‘bread‘};
}

let {egg: a1, milk: a2, bread: a3} = breakfast();    //a1,a2,a3是自己定义的名字
console.log(a1,a2,a3);

 

5.字符模板

‘use strict‘;

let food1 = ‘egg‘, food2 = ‘bread‘;

let str = `今天的早餐是 ${food1} 和 
      ${food2}`;  //通过反斜线引号可以对字符串换行 console.log(str);

 

6.字符串相关函数

‘use strict‘;

let food1 = ‘egg‘, food2 = ‘bread‘;

let str = `今天的早餐是 ${food1} 和 
          ${food2}`; 

console.log(str.startsWith(‘今天‘),str.endsWith(‘bread‘),str.includes(‘早餐‘));  //true true true

 

7.函数默认值

1 ‘use strict‘;
2 
3 function breadfast (food = ‘食物‘, drink = ‘饮料‘) {
4     console.log(`${food} ${drink}`);
5 }
6 
7 breadfast();        //输出默认值
8 breadfast(‘面包‘, ‘啤酒‘);        //输出给定值

 

8.  ...操作符

1 ‘use strict‘;
2 
3 function breakfast (food, drink, ...others) {        //...表示后面除了前面两个参数,其余参数都放在others这个数组里
4     console.log(food, drink, others);
5     console.log(food, drink, ...others);    //将others数组里面的值展开
6 }
7 
8 breakfast(‘面包‘, ‘牛奶‘, ‘培根‘, ‘香肠‘);

 

es2015(es6)基础部分学习笔记(更新中...)