箭头函数
1.this值是静态的,this指向函数声明时的作用域
//未使用箭头函数
let object = {}
function fn() {
console.log(this)
}
fn.bind(object)() //this指向object
//使用箭头函数
let object = {}
let fn = () => { console.log(this) }
fn.bind(object)() //this 指向window
//练习
let name = 'ls'
let object = {
name: 'zs',
fn() { console.log(this.name) },
fn1: () => { console.log(this.name) },
fn2() {
return () => {
console.log(this.name)
}
}
}
object.fn() // 'zs'
object.fn1() // 'ls'
let fn2 = object.fn2()
fn2() //'zs'
扩展运算符
1.将伪数组转换成真实数组
let elements = document.querySelectAll('div')
let array = [...elements]
2.数组对象合并(引用类型只是浅拷贝)
let arr1 = [1,3,5]
let arr2 = [2,4,6]
let arr3 = [...arr1,...arr2]
console.log(arr3) //[1,3,5,2,4,6]
let obj1 = { name: '张三' }
let obj2 = { age: 18 }
let obj3 = { ...obj1,...obj2 }
console.log(obj3) //数据结果 { name: '张三' , age: 18 }
Promise
- 为了解决回调地狱
- 对象的状态不受外界影响。Promise 对象代表一个异步操作,有三种状态:
- pending: 初始状态,不是成功或失败状态
- fulfilled: 意味着操作成功完成
- rejected: 意味着操作失败
//封装promise - todo
let fn =(params) => {
retrun new Promise((resolve,reject) => {
//开启一个异步操作 判断传递过来的值是否为真
setTimeout(() => { params.flag ? resolve(params.value) : reject(params.value) },2000)
})
}
//使用封装的异步操作
fn({ flag: true, value: 'success' }).then(resolved => {
//promise成功
const { flag } = resolved
//根据flag 判断返回新的promise
return flag ? fn({ flag: false, value: '失败1' }) : fn({ flag: true, value: '成功1' })
}).then(resolved => {
const { flag } = resolved
//根据flag 判断返回新的promise
return flag ? fn({ flag: false, value: '失败2' }) : fn({ flag: true, value: '成功2' })
}).catch(error = > {
console.log(error)
})
Set
1.数组去重
let array = [...new Set(['todo1','todo2','todo3','todo1'])]
console.log(array) // ['todo1','todo2','todo3']
2.检测元素是否存在
let name = new Set(['张三','李四','王五'])
console.log(name.has('李四')) //true
3.删除某个元素
let name = new Set(['张三','李四','王五'])
name.delete('李四')
console.log(name) // ['张三','王五']
async和await
- await必须再async函数中
- await右侧一般为promise对象
- await返回的是promise成功的值
- 需要用try/catch捕获异常
//封装promise - todo
let promise = (params) => {
return new Promise((resolve,reject) => {
setTimeout(() => {
params.flag ? resolve(params.value) : reject(params.value)
})
})
}
let fn = async () => {
try {
const { value } = await promise({ flag:false, value: '错误' })
}.catch(error => {
console.log(error)
})
}
防止崩溃的可选链
const user = {
info: {
name: 'zs',
age: 19,
card: ['xxxxxxx','123456789'],
test: []
}
}
console.log(user?.info?.card) // ['xxxxxxx','123456789']
console.log(user?.info?.test) // []
console.log(user?.info?.test1 ?? '-') // '-' 如果没有定义左侧返回右侧。如果是,则返回左侧
console.log(user?.info?.name ?? '-') // 'zs' 如果没有定义左侧返回右侧。如果是,则返回左侧