面试题答案是我自己写的,有不对的地方请评论区指出!!!ღ( ´・ᴗ・` )比心
1.事件循环
async function async1(){
console.log(1);
await async2()
console.log(2);
}
async function async2(){
console.log(3);
}
console.log(4);
async1()
setTimeout(()=>{
console.log(5);
},0)
new Promise((resolve)=>{
console.log(6);
resolve()
}).then(()=>{
console.log(7);
})
console.log(8);
输出顺序:
2.手写Promise.all源码
3.算法:栈
用例1:输入:["1","3","+","6","*"] 输出:24 计算过程:(1+3)*4=24 用例2:输入:["22","5","-","5","/"] 输出:3 计算过程:(22-5)/4=3
function fn(args) {
let stack = [], res = 0, num = 0
for (let i = 0; i < args.length; i++) {
if (args[i] === "+") {
num = Number(stack[stack.length - 2]) + Number(stack[stack.length - 1])
stack.pop()
stack.pop()
stack.push(num)
} else if (args[i] === "-") {
num = Number(stack[stack.length - 2]) - Number(stack[stack.length - 1])
stack.pop()
stack.pop()
stack.push(num)
} else if (args[i] === "*") {
num = Number(stack[stack.length - 2]) * Number(stack[stack.length - 1])
stack.pop()
stack.pop()
stack.push(num)
} else if (args[i] === "/") {
num = Math.floor(Number(stack[stack.length - 2]) / Number(stack[stack.length - 1]))
stack.pop()
stack.pop()
stack.push(num)
} else {
stack.push(Number(args[i]))
}
}
return stack[0]
}
console.log(fn(["1", "3", "+", "6", "*"]));
// console.log(fn(["22","5","-","5","/"]));
4.react hooks写一个从100减到0的倒计时
//App.jsx
import React,{useState,useEffect} from 'react'
export default function App(props){
const [timerID, setTimerID] = useState(null);
const [counter, setCounter] = useState(100);
useEffect(() => {
if(counter > 0){
let timer = setTimeout(() => {
setCounter(counter-1)
}, 1000);
setTimerID(timer)
}else{
console.log("时间到!!!");
}
return () => {
setTimerID(null)
}
},[counter]);
return (
<div>
<p>{counter}秒后将计时结束...</p>
</div>
);
}