数组去重的常用方法,利用Promise实现函数按序执行
//普通数组去重
let ary = [1,2,3,1,2,3,1,2,3]
//方法一 for循环+三目运算
Array.prototype.quchong1 = function (){
let obj = {}
let result = []
for(let i = 0; i< this.length; i++){
obj[this[i]] ? '' : ( obj[this[i]] = result.push(this[i]) )
}
return result
}
console.log(ary.quchong1()) // [1, 2, 3]
// 方法二 过滤filter
Array.prototype.quchong2 = function () {
let result = this.filter(
(item,index,self) => {
return self.indexOf(item) === index
}
)
return result
}
console.log(ary.quchong2()) //[1, 2, 3]
//方法三 reduce + 短路或
Array.prototype.quchong3 = function () {
let obj = {}
let result = this.reduce(
(pre,cur,index)=>{
obj[cur] || (obj[cur] = pre.push(cur))
return pre
},[]
)
return result
}
console.log(ary.quchong3())
//方法四 new Set + 扩展运算符...
Array.prototype.quchong4 = function () {
let result = [...new Set(this)]
return result
}
console.log(ary.quchong4()) //[1, 2, 3]
// 对数组中相同的对象进行去重
let ary2 = [
{name: 'zh'},
{name: 'zh'},
{name: 'yy'},
{name: 'zh'}
]
//方法一 for循环 + 三目运算
Array.prototype.quchong5 = function () {
let obj = {}
let result = []
for ( let i =0; i < ary2.length; i++ ) {
obj[this[i].name] ? '' : obj[this[i].name] = result.push(this[i])
}
return result
}
console.log(ary2.quchong5()) //[ {name: 'zh'},{name: 'yy'}]
//方法二 for循环 + 短路或
Array.prototype.quchong6 = function () {
let obj = {}
let result = []
for ( let i =0; i < ary2.length; i++ ) {
obj[this[i].name] || ( obj[this[i].name] = result.push(this[i]) )
}
return result
}
console.log(ary2.quchong6()) //[ {name: 'zh'},{name: 'yy'}]
//方法三 reduce + 短路或
Array.prototype.quchong7 = function (){
let obj = {}
let result = this.reduce(
(pre,cur,index) => {
obj[cur.name] || ( obj[cur.name] = pre.push(cur) )
return pre
},[]
)
return result
}
console.log(ary2.quchong7()) //[ {name: 'zh'},{name: 'yy'}]
利用Promise实现函数按序执行
function a () {
setTimeout(
()=>{ console.log(1)},3000
)
}
function b () {
setTimeout(
()=>{ console.log(2)},2000
)
}
function c () {
setTimeout(
()=>{ console.log(3)},1000
)
}
a()
b()
c()
// 执行输出结果为 3 2 1
// 利用promise 实现 函数按序执行
function a () {
return new Promise(
(resolve,reject) => {
setTimeout(
()=>{
console.log(1)
resolve()
},3000
)
}
)
}
function b () {
return new Promise(
(resolve,reject) => {
setTimeout(
()=>{
console.log(2)
resolve()
},2000
)
}
)
}
function c () {
return new Promise(
(resolve,reject) => {
setTimeout(
()=>{
console.log(3)
resolve()
},1000
)
}
)
}
// 方法一
a().then(b).then(c) //执行结果 1 2 3
// 方法二
async function d () {
await a()
await b()
await c()
}
d() //执行结果 1 2 3