GeQin

导航

ES6常用方法总结

1、声明变量用let,声明常量用const(定义唯一的值),都没有预解释,也不存在变量提升;

2、箭头函数:有如下两种写法

    1)、表达式(函数体只有一行代码)

       a)、let fn = p => p ;   //一个参数

       b)、let fn = (n,m) => n+m;  //两个参数

       c)、let fn = () => '我是没有参数的 '; //不带参数

    2)、函数体(函数体有多行代码)

         let fn = (n, m) => {

              let total = n+m;

             return total;

        }

3、变量的解构赋值

   1)数组

   let [a, b, c] = [1, 2, 3];
console.log(a); //1
console.log(b); //2
console.log(c); //3
2)对象
   let {a , b} = {a:'111',b:'222'};
console.log(a); //111
console.log(b); //222
4、扩展运算符:三个点(...)该运算符将一个数组,变为参数序列,所以不再需要ES5的apply方法。
   function add(x, y) {
return x + y;
}
let numbers = [4, 38];
let result = add(...numbers);
console.log(result); // 42
5、模板字符串
let name = 'Kiki',
let age = 18;
//ES5写法
let str = name + '的年龄是' + age + ‘岁了!’;
//ES6写法(反引号:英文状态下,键盘第二行第一个字符)
let str = `${name}的年龄是${age}岁了!`;
6、Set和Map数据结构
1)Set 类似于数组,但是成员的值都是唯一的,不重复;本身也是一个构造函数,可以用new Set()来生成Set数据结构。
   const set = new Set([1, 2, 3, 4, 4]);
console.log(...set); //1 2 3 4
2)Map js的对象(Object),本质上是键值对的集合。
   let a = new Map();
let b = {};
a.set(b,'hello');
a.get(b); //hello
a.has(b); //true
a.delete(b);
a.has(b); //false

//Map 也可以接受一个数组作为参数
   let person = new Map([
['name','kiki'],
['age',18]
]);
person.has('name'); //true
person.has('age'); //true
person.get('name'); //kiki
person.get('age'); //18
7、定义一个类及类的继承
1)、通过class创建类
2)、通过constructor创建构造函数
3)、函数名(){
//公有属性和方法
}
   class Person{
constructor(name,age){
this.name = name;
this.age = age;
}
makePerson(){
return 'my name is ' + this.name + ', my age is ' + this.age
}
}

let person1 = new Person('kiki',18);
let p = person1.makePerson();
console.log(p);//my name is this.name , my age is this.age
  4)、static 函数名(){} 静态的属性和方法,给类上添加的私有属性和方法
5)、class 子类 extend 父类 { //子类继承父类
constructor (name, age, color){
super(name, age); //必须写,调用父类的constructor(name, age)
this.color = color;
}
}
8、for-of循环:遍历所有数据结构的方法,可获取键值,而原有的for-in循环可获取键名
   const arr = ['red', 'green', 'blue'];
for(let v of arr) {
console.log(v); // red green blue
}
for(let k in arr){
console.log(k); //0 1 2
}

posted on 2017-08-09 10:36  GeQin  阅读(246)  评论(0编辑  收藏  举报