ES6常用新特性总结

装载于:https://blog.csdn.net/miaorunqing/article/details/54964815,用于学习保存留档

1.let && const

let命令也用于声明对象,但是作用域为局部。

{
    let a = 10;
    var b = 1;
}
  • 1
  • 2
  • 3
  • 4

在函数外部可以获取到b,获取不到a,因此例如for循环计数器就适合使用let。

const用于声明一个常量,设定后值不会再改变。

const PI = 3.1415;
PI // 3.1415
PI = 3;
  • 1
  • 2
  • 3

强行对其进行重新赋值会报错。

2.iterable类型

为了统一集合类型,ES6标准引入了新的iterable类型,Array、Map和Set都属于iterable类型,具有iterable类型的集合可以通过新的for … of循环来遍历。

var a = ['A', 'B', 'C'];
var s = new Set(['A', 'B', 'C']);
var m = new Map([[1, 'x'], [2, 'y'], [3, 'z']]);
for (var x of a) { // 遍历Array
    alert(x);
}
for (var x of s) { // 遍历Set
    alert(x);
}
for (var x of m) { // 遍历Map
    alert(x[0] + '=' + x[1]);
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

Map相关操作方法如下,Set同理:

var m = new Map(); // 空Map
m.set('Adam', 67); // 添加新的key-value
m.set('Bob', 59);
m.has('Adam'); // 是否存在key 'Adam': true
m.get('Adam'); // 67
m.delete('Adam'); // 删除key 'Adam'
m.get('Adam'); // undefined
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

3.解构赋值

ES6 允许按照一定模式,从数组和对象中提取值,对变量进行赋值,这被称为解构(Destructuring)。 
例如数组:

let [a, b, c] = [1, 2, 3];
//等同于
let a = 1;
let b = 2;
let c = 3;
  • 1
  • 2
  • 3
  • 4
  • 5

对象的解构赋值:获取对象的多个属性并且使用一条语句将它们赋给多个变量。

>var {
  StyleSheet,
  Text,
  View
} = React;
  • 1
  • 2
  • 3
  • 4
  • 5

等同于

var StyleSheet = React.StyleSheet
...
  • 1
  • 2

4.箭头函数

ES6中新增箭头操作符用于简化函数的写法,操作符左边为参数,右边为具体操作和返回值。

var sum = (num1, num2) => { return num1 + num2; }
//等同于
var sum = function(num1, num2) {
    return num1 + num2;
 };
  • 1
  • 2
  • 3
  • 4
  • 5

箭头函数还修复了this的指向,使其永远指向词法作用域:

var obj = {
    birth: 1990,
    getAge: function () {
        var b = this.birth; // 1990
        var fn = () => new Date().getFullYear() - this.birth; // this指向obj对象
        return fn();
    }
};
obj.getAge(); // 25
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

5.延展操作符

通过它可以将数组作为参数直接传入函数:

var people=['Wayou','John','Sherlock'];
function sayHello(people1,people2,people3){
    console.log(`Hello ${people1},${people2},${people3}`);
}
//改写为
sayHello(...people);//输出:Hello Wayou,John,Sherlock 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

在函数定义时可以通过…rest获取定义参数外的所有参数:

function foo(a, b, ...rest) {
    console.log('a = ' + a);
    console.log('b = ' + b);
    console.log(rest);
}

foo(1, 2, 3, 4, 5);
// 结果:
// a = 1
// b = 2
// Array [ 3, 4, 5 ]
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

6.类

ES6提供了更接近传统语言的写法,引入了Class(类)这个概念,作为对象的模板。通过class关键字,可以定义类,与多数传统语言类似。

//定义类
class Point {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }

  toString() {
    return '(' + this.x + ', ' + this.y + ')';
  }
}

猜你喜欢

转载自blog.csdn.net/twtcqw2008/article/details/80565730