ES6新特性

1.箭头函数:

 箭头函数不需要参数或需要多个参数,就使用一个圆括号代表参数部分。

 var f = () => 5;
 var sum = (num1, num2) => num1 + num2;

 箭头函数的代码块部分多于一条语句,要使用大括号将它们括起来,并且用return语句返回。

var sum = (num1, num2) => { return num1 + num2; }

 由于大括号被解释为代码块,所以如果箭头函数直接返回一个对象,必须在对象外面加上括号。

 var getTempItem = id => ({ id: id, name: "Temp" });

 箭头函数可以与变量解构结合使用。

 const full = ({ first, last }) => first + ' ' + last;

 等同于

 function full(person) {
  return person.first + ' ' + person.last;
 }

 简化回调函数。
 正常函数写法

 [1,2,3].map(function (x) {
     return x * x;
 });

箭头函数写法

[1,2,3].map(x => x * x);

注意:
1)函数体内的this对象,就是定义时所在的对象,而不是使用时所在的对象。
2)不可以当作构造函数,也就是说,不可以使用new命令,否则会抛出一个错误。
3)不可以使用arguments对象,该对象在函数体内不存在。如果要用,可以用Rest参数代替。
4)不可以使用yield命令,因此箭头函数不能用作Generator函数。
箭头函数没有自己的this,而是引用外层的this

2.rest参数(...)

用途:

可以看作是扩展运算符正运算,可以将数组转化为参数列表

console.log(1,...[2,3,4],5); //1 2 3 4 5

可以替代apply方法

Math.max.apply(null,[14,3,7])
console.log(Math.min(...[14,3,7]));

可以用于合并数组

[1,2].concat([3])
console.log([1,2,...[3]]);

用于与解构赋值结合 只能放在参数的最后一位,否则会报错

const [first, ...rest] = [1, 2, 3, 4, 5];
console.log(first); // 1
console.log(rest); // [2, 3, 4, 5]
const [first, ...rest] = [];
console.log(first); // undefined
console.log(rest); // []
const [first, ...rest] = ["foo"];
console.log(first); // "foo"
console.log(rest); // []

用于函数返回多个值

var dateFields = readDateFields(database);
var d = new Date(...dateFields);

从数据库取出一行数据,通过扩展运算符,直接将其传入构造函数Date
可以将字符串转为数组

console.log([...'hello']);
[ "h", "e", "l", "l", "o" ]

此方法能够正确识别32位的Unicode字符

function length(str) {
    return [...str].length;
console.log([...str].length);
}
length('xuD83DuDE80y'); // 3

实现了Iterator接口的对象

var nodeList = document.querySelectorAll('div');
var array = [...nodeList];

任何Iterator接口的对象,都可以用扩展运算符转为真正的数组
Map和Set结构,Generator函数都可以使用扩展运算符

let map = new Map([
  [1, 'one'],
  [2, 'two'],
  [3, 'three'],
]);
let arr = [...map.keys()]; // [1, 2, 3]
var go = function*(){
  yield 1;
  yield 2;
  yield 3;
};
[...go()] // [1, 2, 3] 

length属性定义:该函数预期传入的参数个数

原文地址:https://www.cnblogs.com/wccc/p/9868054.html