es6学习笔记2

119 阅读2分钟

1.5函数扩展运算符、箭头函数

...扩展运算符

将一个数组分割,并将各项作为分离的参数传给函数。

const arr = [10,20,23,24]
用es5对数组进行处理取最大值:
Math.max.apply(arr)
es6则可以使用扩展运算符:
Math.max(...arr)

=>箭头函数

function(){}相当于()=>{}。参数=>返回值。返回值为对象的时候需要()。
const add = function(a,b){return a+b}等价于
const add = (a,b) => {return a+b}
let add = val => val
let add = (val1, val2) => val1 + val2
let fn = (() => {return () => { a }})()

1.6箭头函数this指向以及注意事项。

es5中的this指向取决于调用该函数的上下文对象。 .bind(this) es5箭头函数里的this没有指向,箭头函数内部this值只能通过查找作用域链来确定,一旦使用箭头函数,当前不存在作用域链。

注意事项:

使用箭头函数函数内部没有arguments(无作用域链,指向window) let add = (a, b)=> { console.log(arguments); //error:not defined return a+b; }
箭头函数不能使员工new关键字来实例化对象。(箭头函数不是个对象,只是表达式) let Person = ()=>{} let people = new Person() //error: not a consttuctor

1.7解构赋值

语法:

对对象解构

let type = node.type;let name = node.name;let index = node.index //es5
let {type, name, index} = node // 完全解构
let {type} = node // 不完全解构
let {type, ...res} = node

对数组解构

let [a, b] = [1, 2]

1.8扩展的对象功能

es6对象直接写入变量和函数,作为其属性和方法。

const person ={
name, //name: name
age,
say(){} //say:function(){}
}

对象的方法

is() //比较严格相等
Object.is(NaN,NaN) //TRUE
assign() //对象的合并
Object.assign({},{a:1},{b:2}) //返回合并之后新对象

1.9 Symbol原始数据类型

独一无二 ,定义对象私有变量

const name = Symbol('name');
let obj = {
[name]: 'tom'
}
取值时应该使用obj[name]不能用obj.name。
两个方法获取Symbol声明的属性名(作为对象的key):
Object.getOwnPropertySymbols(obj);
Reflect.onwKeys(obj)

1.10 Set集合数据类型

无重复值的有序列表

set声明的集合可以使用add,delete,forEach(key,value),
其中forEach中的键和值是一致的。
可以用扩展运算符将set数据类型转换为数组。 用
new Set(arr)将数组转换为集合。

1.10 Map集合数据类型

可以理解为有key和对应value的Set类型

map声明的集合有set,has,delete,clear方法。