async/await学习
async用法1234async fn() {}const fn = async () => {}const fn = async function() {}let obj = { async fn() {} }
Promise学习(2)
Promise.all()12345678910111213function setTime(time = 0, isSuccess = true) { return new Promise((res, rej) => { setTimeout(() => { console.log(666); isSuccess && res(`成功:${time}`); !isSuccess && rej(`失败:${time}`); }, time); });}Promise.all([setTime(100), setTime(200), setTime(300)]) .then(res => console.log(res)) // (3) ["成功:100", "成功:200", "成功:300"] .catch(err...
Promise学习
Promise的状态Promise有三个状态: pending:[待定]初始状态 fulfilled:[实现]操作成功 rejected:[被否决]操作失败 当promise状态发生改变,就会触发then()里的响应函数处理后续步骤。promise状态一经改变,不会再变。 Promise对象的状态改变,只有两种可能: 从pending变为fulfilled。 从pending变为rejected。 这两种情况只要发生,状态就凝固了,不会再变了。 基本使用知识点123456789101112131415161718let p = new Promise((res, rej) => {let t = new Date(), s = t.getSeconds();if(s % 2) { res(s);}else{ rej(s, "参数二");}});# 调用方式1p.then(res => console.log(res, "成功")) ...
js数组排序
假设现在有一个这样的数组: 1let arr = [3, 5, 1, 2, 6, 0, 4]; 我们需要对他进行排序,从小到大。 方法一:使用sort方法12345arr.sort(function(a, b) { return a - b;});console.log(arr);// [0, 1, 2, 3, 4, 5, 6] 如果sort方法,不传入方法的话,某种情况下他是会有问题的。举个例子: 123let _arr = [0, 1, 5, 10, 15, 51];_arr.sort();// [0, 1, 10, 15, 5, 51] 为了实现升序,sort()方法会调用每个数组项的toString()转型方法,然后比较得到的字符串,以确定如何排序。即使数组中的每一项都是数值,sort()方法比较的也是字符串。为了更好的实现排序,sort()方法可以接收一个比较函数作为参数,以便我们指定哪个值位于那个值的前面。 方法二:使用冒泡排序方法12345678910for(let i = 0 ; i < arr.length - 1 ; i++)...