猫眼前端一面(转正实习)
问问简历
每次面试都问:你做过移动端吗,只做过pc项目的移动端适配,基于rem
说输出
const [count, setCount] = useState(0);
useEffect(() => {
const interval = setInterval(() => {
console.log(count); // 这里如果直接用 count,会出现闭包问题
setCount(count+ 1);
}, 1000);
return () => clearInterval(interval);
}, []); // 空依赖数组,确保只运行一次
全输出0
💡 为什么闭包会导致 count 不更新?
因为 setInterval 的回调捕获了 useEffect 执行时的 count 值(第一次是 0),之后就一直用这个旧值,除非依赖数组里放 count,但那会导致重复创建定时器。
正确做法就是用 函数式更新 setCount(prev => prev + 1) 来获取最新状态。
useEffect(() => {
const interval = setInterval(() => {
console.log(count); // 这里如果直接用 count,会出现闭包问题
setCount(prev => prev + 1); // 用函数式更新解决闭包问题
}, 1000);
return () => clearInterval(interval);
}, []); // 空依赖数组,确保只运行一次
面试官:还能怎么做?不会 哈哈
- 在依赖数组里放 count(重建定时器)
useEffect(() => {
const interval = setInterval(() => {
console.log(count);
setCount(count + 1);
}, 1000);
return () => clearInterval(interval);
}, [count]); // 每次 count 变化都会重建定时器
- 用 useRef 存储最新值,定时器读 ref.current
const countRef = useRef(0);
const [count, setCount] = useState(0);
useEffect(() => {
countRef.current = count; // 同步最新值到 ref
}, [count]);
useEffect(() => {
const interval = setInterval(() => {
console.log(countRef.current);
setCount(prev => prev + 1);
}, 1000);
return () => clearInterval(interval);
}, []);
手撕
记录0~n范围内,1出现的次数,不能用两轮for
按位分析法(数学规律解法)写不出来 给换了道题
数组L型输出
var obj = {
name: 2,
add: function() {
this.name = 3;
(function(){
console.log(this.name);
this.name = 4;
})()
console.log(this.name);
}
}
obj.add();
//在非严格模式下,IIFE 中的 this 指向全局对象,可以正常访问 this.name
//undefined 3
//严格模式下,IIFE 中的 this 不再指向全局对象,而是 undefined
//当尝试访问 undefined.name 时,会抛出 TypeError
怎么把IIFE的this指向obj?
- 用 .call(obj) 或 .apply(obj)
(function(){
console.log(this.name);
this.name = 4;
}).call(this); // 这里的 this 是 obj,因为 add() 是通过 obj 调用的
- 用箭头函数(继承外层 this)
add: function() {
this.name = 3;
(() => {
console.log(this.name); // this 继承自 add 的调用者 obj
this.name = 4;
})();
console.log(this.name);
}
还有道事件循环题目
我真服了,不比大厂简单