解构赋值
ES6中允许从数组中提取值,按照对应位置,对变量赋值。对象也可以实现解构。
数组解构
将数组中的元素按对应位置赋值给变量
在等号的左边 []
表示解构
let [a, b, c] = [1, 2, 3] console.log(a) console.log(b) console.log(c) console.log('-----------------------') let [d, e] = [4, 5, 6] console.log(d) console.log(e)
1 2 3 ----------------------- 4 5
如果解构不成功,变量的值为undefined
及数组中没有值与变量对应
let [a, b, c, d, e, f, g] = [1, 2, 3] console.log(a) console.log(b) console.log(c) console.log(d) console.log(e) console.log(f) console.log(g)
1 2 3 undefined undefined undefined undefined
对象解构
等号左边的{}
表示对象解构
根据变量名去匹配对象的属性,如果存在同名的属性,则将属性值赋值给变量,如果不存在同名的属性,则变量为undefined
let person = { name: 'zs', age: 12, from: 'bj', like: '无' } let {name} = person console.log(name) let {age} = person console.log(age) let {from, like} = person console.log(from) console.log(like) let {lili} = person console.log(lili)
zs 12 bj 无 undefined
对象解构时可以对解构出来的变量进行重命名
使用:
冒号前面的为要解构的属性,冒号后面的为别名
let person = { name: 'zs', age: 12, from: 'bj', like: '无' } let {name:n, age:a} = person console.log(n) console.log(a)
zs 12
箭头函数
语法:
(参数列表) => {函数体}
一般把箭头函数赋值给变量
const fn = (参数列表) => {函数体}
调用函数
fn()
如果函数体中只有一句代码,且代码的结果就是返回值,可以省略花括号
const fn = (a, b) => a+b let res = fn(1, 2) console.log( res )
3
如果需要传入的参数只有一个,圆括号也可以省略
const fn = a => a let res = fn(1) console.log( res )
1
箭头函数中的this关键字
箭头函数不绑定this关键字,箭头函数中的this,指向的为函数定义位置的上下文的this
即箭头函数没有自己的this
箭头函数的this,为箭头函数定义位置的this
函数的call,可以改变this的指向
const obj = { na: 'zs', age: 13 } function fn() { console.log(this) return () => { console.log(this) } } // resfn为fn函数中返回的箭头函数 // 所以resfn也为函数 // fn的this指向obj const resfn = fn.call(obj) resfn()
{ na: 'zs', age: 13 } { na: 'zs', age: 13 }
箭头函数面试题
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <script> var obj = { age: 20, say: () => { alert( this.age ) } } obj.say(); </script> </body> </html>
问警告框的输出
由于箭头函数中的this指向定义位置的this,而obj的this指向window对象,window对象中未定义age全局变量,所以输出为undefined。
在window中定义age变量:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <script> var age = 100 var obj = { age: 20, say: () => { alert( this.age ) } } obj.say(); </script> </body> </html>
剩余参数
剩余参数语法允许将一个不定数量的参数表示为一个数组。
function sum( ...args ) { console.log( args ) } sum(10,20,20)
[ 10, 20, 20 ]
剩余参数可以接受多个参数为一个数组。
剩余参数与结构配合
当要结构的数组的元素个数大于变量的个数,会将剩余的元素全部给剩余参数。
let nums = [1,2,3,4,5,6,7] let [a,b,c,d,...args] = nums console.log(a) console.log(b) console.log(c) console.log(d) console.log(args)
1 2 3 4 [ 5, 6, 7 ]