1. websocket 转 promise
send({type: 'getUserInfo'})
{type:'userInfo', payload: {}}
const res = await getMessage({type: 'getUserInfo'},{type:'userInfo'});
const ws = window.ws;
// ws.addEventListener('message', callback);
const time = 5000;
const getMessage = async function (msg,filter) {
let timer = null;
let timePromise = new Promise((resolve, reject) => {
timer = setTimeout(() => {
resolve()
},time)
})
let getMessage2 = new Promise((resolve, reject) => {
ws.onmessage((res)=>{
if(res.type === filter.type) {
resolve(res)
}
});
ws.send(msg)
})
return Promise.race([timePromise, getMessage2]).finally(()=>{
timer = null
})
}
2. 利用html css 样式,div垂直body居中,div中的text垂直居中,div的高度等于body高度的一半 100vh
<body style="display: flex; align-items: center; justify-content: center; height: 100vh">
<div style="text-align: center;height: 50%;">
text
</div>
</body>
flex: 1;
3. [1,3,4,5,6,8,9] => ['1','3-6','8-9']
let res = []
let fastP = 1, slowP = 0
while(fastP < arr.length) {
if(arr[fastP] - 1 > arr[fastP - 1]) {
let tmpStr = ''
if(slowP === fastP - 1) {
tmpStr = tmpStr + arr[slowP]
} else {
tmpStr = arr[slowP] + '-' + arr[fastP - 1]
}
res.push(tmpStr)
slowP = fastP
}
fastP ++
}
4. 发布订阅
let subject = new Subject();
let dispose = subject.listen('message', (payload)=>{
console.log(payload)
});
// dispose(); 销毁事件
subject.emit('message', {
name: 'zs'
});
// 实现Subject
class Subject{
bus = {}
emit(event, payload) {
this.bus[event].forEach((callback)=>{callback(payload)})
}
listen(event, callback){
if(!this.bus[event]){
this.bus[event] =[];
}
this.bus[event].push(callback);
// callback(this.payloads[event])
// todo return dispose
return ()=>{
this.bus[event] = this.bus[event].filter(item=>item===callback)
}
}
}
把对象转换成数组
const obj = { a: 1, b: 2, c: 3 };
const arr = Object.entries(obj);
console.log(arr); // [["a", 1], ["b", 2], ["c", 3]]
flex: 1 的含义
需要注意的是,flex: 1 只是 flex-grow 的简写形式
它将 flex-grow、flex-shrink 和 flex-basis 设置为默认值,即 flex: 1 1 0。
如果希望指定不同的 flex-grow、flex-shrink 和 flex-basis 值,可以使用完整的 flex 属性写法。
标签:flex,arr,fastP,一面面,bus,面经,let,event,百度 From: https://www.cnblogs.com/zjy4fun/p/17512644.html