1.手写promise.all
// promise.all简单实现
Promise.customAll = function(promiseArr) {
const arr = Array.from(promiseArr)
let results = []
let counter = 0 // 异步结果成功计数,该数为arr.len时说明所有异步都执行成功
let len = arr.length
return new Promise((resolve,reject)=> {
for(let i = 0;i<len;i++) {
Promise.resolve(arr[i]).then((res)=> {
counter ++
results[i] = res
if(counter === len) {
resolve(results)
}
},(err)=> {
reject(err)
})
}
})
}
2.发布-订阅
// 发布-订阅 event调度中心
function Event() {
this.handlers = {}
}
Event.prototype.addEventListener = function (type, hanler) {
if (!this.handlers.hasOwnProperty(type)) {
this.handlers[type] = []
}
this.handlers[type].push(hanler)
}
Event.prototype.disPatchEvent = function (type, ...params) {
if (!this.handlers.hasOwnProperty(type)) {
return new Error('未注册该事件')
}
this.handlers[type].forEach((hanler) => {
hanler(...params)
})
}
Event.prototype.removeEventListener = function (type, hanler) {
if (!this.hasOwnProperty(type)) {
return new Error('未注册该事件')
}
if (!hanler) {
delete this.handlers[type]
return
}
const ids = this.handlers[type].findIndex((el) => el === hanler)
if (ids === -1) {
return new Error('未绑定该事件')
}
this.handlers[type].splice(ids, 1)
if (this.handlers[type].length === 0) {
delete this.handlers[type]
}
}
3.环形矩阵
function snake(n) {
let arr = []
// 初始化数组元素全为0
for(let i = 0;i<n;i++) {
arr.push([])
for(let j = 0;j<n;j++) {
arr[i].push(0)
}
}
let num = 1
let x = 0,y=0;
arr[x][y] = 1 // 第一个元素为1
while(num < n*n) {
while(y+1<n && arr[x][y+1] ==0) arr[x][++y] = ++num
while(x+1<n && arr[x+1][y] ==0) arr[++x][y] = ++num
while(y-1>=0 && arr[x][y-1] ==0) arr[x][--y] = ++num
while(x-1>=0 && arr[x-1][y] ==0) arr[--x][y] = ++num
}
for(let m = 0;m<arr.length;m++) {
console.log(arr[m])
}
}
snake(3)
console.log('**********************')
snake(4)
结果:
4. url 参数获取
// 获取url query参数
const getQuery = ()=> {
const query = window.location.href.split('?')[1]
const mapArr = query.split('&')
let queryObj = {}
mapArr.forEach((item)=> {
let keyValue = item.split('=')
queryObj[keyValue[0]] = keyValue[1]
})
return queryObj
}
5. 最长不重复子串
subStr (s) {
const Obj = {}
for (let i = 0; i < s.length; i++) {
Obj[i] = []
Obj[i].push(s[i])
}
for (let k = 0; k < s.length; k++) {
for (let m = k + 1; m < s.length; m++) {
if (s[m] === s[k]) {
break
} else {
if (Obj[k].indexOf(s[m]) === -1) {
Obj[k].push(s[m])
} else {
break
}
}
}
}
console.log(Obj)
}