【详细精选】前端面试题(2027精选附详细解答)包含10w数据展示优化、前端核心 - i <
→ DOM节点
2. 构建CSSOM树
/* CSS → CSSOM树 */
body { font-size: 16px; }
div { color: red; }
3. 渲染树构建
结合DOM和CSSOM排除不可见元素(display: none)
4. 布局(重排)
// 计算每个元素的位置和大小
// 触发重排的操作:
element.style.width = '100px';
element.style.height = '200px';
window.getComputedStyle(element);
5. 绘制(重绘)
// 填充像素
// 触发重绘的操作:
element.style.color = 'red';
element.style.backgroundColor = '#fff';
6. 合成
// GPU加速的图层合成
element.style.transform = 'translateX(100px)'; // 触发合成层
优化建议
// 避免强制同步布局
function badExample() {
// 读取 → 写入 → 读取 → 写入
const width = element.offsetWidth; // 触发重排
element.style.width = width + 10 + 'px'; // 触发重排
}
function goodExample() {
// 读取 → 读取 → 写入 → 写入
const width = element.offsetWidth;
const height = element.offsetHeight;
element.style.width = width + 10 + 'px';
element.style.height = height + 10 + 'px';
}
7. 节流和防抖
防抖(Debounce)
// 原理:在事件被触发n秒后再执行,如果在这n秒内又被触发,则重新计时
function debounce(fn, delay) {
let timer = null;
return function(...args) {
const context = this;
// 清除之前的定时器
clearTimeout(timer);
// 设置新的定时器
timer = setTimeout(() => {
fn.apply(context, args);
}, delay);
};
}
// 使用场景:搜索框输入、窗口resize
const searchInput = document.getElementById('search');
searchInput.addEventListener('input', debounce(function() {
console.log('搜索:', this.value);
}, 500));
节流(Throttle)
// 原理:规定在一个单位时间内,只能触发一次函数
// 时间戳实现
function throttle(fn, delay) {
let lastTime = 0;
return function(...args) {
const now = Date.now();
const context = this;
if (now - lastTime >= delay) {
fn.apply(context, args);
lastTime = now;
}
};
}
// 定时器实现
function throttle(fn, delay) {
let timer = null;
let lastArgs = null;
return function(...args) {
lastArgs = args;
if (!timer) {
timer = setTimeout(() => {
fn.apply(this, lastArgs);
timer = null;
}, delay);
}
};
}
// 使用场景:滚动加载、按钮点击
window.addEventListener('scroll', throttle(function() {
console.log('滚动位置:', window.scrollY);
}, 100));
结合版(加强版节流)
function enhancedThrottle(fn, delay, options = {}) {
const { leading = true, trailing = true } = options;
let timer = null;
let lastTime = 0;
let lastArgs = null;
return function(...args) {
const context = this;
const now = Date.now();
// 计算剩余时间
const remaining = delay - (now - lastTime);
// 更新参数
lastArgs = args;
if (remaining <= 0) {
// 时间到了,执行函数
if (timer) {
clearTimeout(timer);
timer = null;
}
if (leading) {
fn.apply(context, args);
}
lastTime = now;
} else if (!timer && trailing) {
// 设置定时器,确保最后一次执行
timer = setTimeout(() => {
fn.apply(context, lastArgs);
timer = null;
lastTime = Date.now();
}, remaining);
}
};
}
8. 闭包
基本概念
// 闭包:能够访问其他函数作用域中变量的函数
function outer() {
const name = "John"; // 局部变量
function inner() {
console.log(name); // 访问外部函数的变量
}
return inner; // 返回内部函数
}
const closureFn = outer();
closureFn(); // "John"
实际应用
1. 数据私有化
function createCounter() {
let count = 0; // 私有变量
return {
increment() {
count++;
return count;
},
decrement() {
count--;
return count;
},
getCount() {
return count;
}
};
}
const counter = createCounter();
console.log(counter.increment()); // 1
console.log(counter.increment()); // 2
console.log(counter.getCount()); // 2
2. 函数工厂
function createMultiplier(multiplier) {
return function(x) {
return x * multiplier;
};
}
const double = createMultiplier(2);
const triple = createMultiplier(3);
console.log(double(5)); // 10
console.log(triple(5)); // 15
3. 模块模式
const myModule = (function() {
let privateVar = 0;
function privateMethod() {
return privateVar;
}
return {
publicMethod() {
privateVar++;
return privateMethod();
}
};
})();
console.log(myModule.publicMethod()); // 1
内存管理
// 闭包可能导致内存泄漏
function leakMemory() {
const largeArray = new Array(1000000).fill('data');
return function() {
console.log('仍然持有largeArray的引用');
// largeArray不会被垃圾回收
};
}
// 解决方案:及时释放引用
function noLeak() {
let largeArray = new Array(1000000).fill('data');
const result = largeArray.length;
// 使用完后设为null
largeArray = null;
return function() {
console.log('不持有largeArray的引用');
return result;
};
}
9. 浏览器线程
主要线程
1. 主线程(UI线程)
// 负责:DOM渲染、JavaScript执行、用户交互
// 注意:JavaScript是单线程的
console.log(1);
setTimeout(() => console.log(2), 0);
console.log(3);
// 输出:1, 3, 2(因为有事件循环)
2. 浏览器内核线程
GUI渲染线程:解析HTML/CSS,构建DOM树JavaScript引擎线程:执行JavaScript代码事件触发线程:管理事件队列定时器触发线程:setTimeout/setInterval异步HTTP请求线程:XMLHttpRequest
事件循环机制
// 微任务(Microtask) vs 宏任务(Macrotask)
console.log('script start'); // 同步任务
setTimeout(() => {
console.log('setTimeout'); // 宏任务
}, 0);
Promise.resolve()
.then(() => {
console.log('promise1'); // 微任务
})
.then(() => {
console.log('promise2'); // 微任务
});
console.log('script end');
// 执行顺序:
// 1. script start
// 2. script end
// 3. promise1
// 4. promise2
// 5. setTimeout
Web Workers
// 主线程
const worker = new Worker('worker.js');
worker.postMessage({ data: 'Hello' });
worker.onmessage = function(event) {
console.log('收到worker消息:', event.data);
};
// worker.js(另一个线程)
self.onmessage = function(event) {
const result = heavyComputation(event.data);
self.postMessage(result);
};
function heavyComputation(data) {
// 耗时操作
return data.toUpperCase();
}
10. Vue3 vs Vue2区别
核心差异对比表
特性Vue2Vue3响应式原理Object.definePropertyProxyComposition APIOptions APIComposition API + Options API性能较慢更快(打包体积小40%)TypeScript支持一般完善Fragment不支持支持多根节点Teleport不支持支持Suspense不支持支持Tree-shaking有限更好的支持
响应式系统
// Vue2响应式
const data = { count: 0 };
Object.defineProperty(data, 'count', {
get() {
console.log('获取count');
return value;
},
set(newValue) {
console.log('设置count');
value = newValue;
}
});
// Vue3响应式
const data = { count: 0 };
const proxy = new Proxy(data, {
get(target, key) {
console.log(`获取${key}`);
return target[key];
},
set(target, key, value) {
console.log(`设置${key}`);
target[key] = value;
return true;
}
});
Composition API示例
性能优化
// Vue3的静态提升
const _hoisted_1 = { id: "app" }; // 静态节点提升
const _hoisted_2 = /*#__PURE__*/createVNode("div", null, "静态内容"); // 静态节点
// Vue3的Patch Flag
const vnode = {
type: 'div',
props: { id: 'app', class: 'container' },
children: [
{ type: 'span', children: '动态内容', patchFlag: 1 /* TEXT */ }
]
};
11. new关键字
实现原理
// new关键字的作用
function Person(name) {
this.name = name;
}
const john = new Person('John');
// 模拟new的实现
function myNew(constructor, ...args) {
// 1. 创建一个空对象
const obj = {};
// 2. 将对象的原型指向构造函数的prototype
Object.setPrototypeOf(obj, constructor.prototype);
// 3. 将构造函数的this绑定到新对象
const result = constructor.apply(obj, args);
// 4. 如果构造函数返回对象,则返回该对象,否则返回新对象
return result instanceof Object ? result : obj;
}
const john2 = myNew(Person, 'John');
详细步骤分析
function Animal(name) {
this.name = name;
this.speak = function() {
return `${this.name} makes a noise`;
};
// 如果构造函数返回一个对象,new表达式会返回这个对象
// return { custom: 'object' };
}
Animal.prototype.eat = function() {
return `${this.name} eats food`;
};
// 使用new
const animal = new Animal('Dog');
// 等同于
const animal = {};
animal.__proto__ = Animal.prototype;
Animal.call(animal, 'Dog');
12. bind、call、apply的区别
基本用法对比
const person = {
name: 'John',
greet: function(greeting, punctuation) {
return `${greeting}, ${this.name}${punctuation}`;
}
};
const anotherPerson = { name: 'Jane' };
// call:立即调用,参数逐个传递
person.greet.call(anotherPerson, 'Hello', '!'); // "Hello, Jane!"
// apply:立即调用,参数数组传递
person.greet.apply(anotherPerson, ['Hi', '!!']); // "Hi, Jane!!"
// bind:返回新函数,不立即调用
const boundGreet = person.greet.bind(anotherPerson, 'Hey');
boundGreet('?'); // "Hey, Jane?"
手写实现
// 实现call
Function.prototype.myCall = function(context, ...args) {
// 如果context是null或undefined,指向全局对象
context = context || window;
// 创建唯一key,避免属性冲突
const fnKey = Symbol('fn');
// 将函数作为context的方法
context[fnKey] = this;
// 执行函数
const result = context[fnKey](...args);
// 删除添加的方法
delete context[fnKey];
return result; 拼多多帮助力入口
};
// 实现apply
Function.prototype.myApply = function(context, argsArray = []) {
context = context || window;
const fnKey = Symbol('fn');
context[fnKey] = this;
const result = context[fnKey](...argsArray);
delete context[fnKey];
return result;
};
// 实现bind
Function.prototype.myBind = function(context, ...bindArgs) {
const originalFn = this;
return function boundFn(...callArgs) {
// 判断是否作为构造函数调用(使用new)
const isConstructorCall = new.target !== undefined;
if (isConstructorCall) {
// 如果是new调用,忽略绑定的this
return new originalFn(...bindArgs, ...callArgs);
} else {
// 普通调用,使用绑定的this
return originalFn.apply(context, [...bindArgs, ...callArgs]);
}
};
};
实际应用场景
// 1. 借用数组方法处理类数组对象
function sum() {
// arguments是类数组,没有数组方法
const args = Array.prototype.slice.call(arguments);
return args.reduce((acc, val) => acc + val, 0);
}
// 2. 构造函数继承
function Parent(name) {
this.name = name;
}
function Child(name, age) {
Parent.call(this, name); // 继承属性
this.age = age;
}
// 3. 事件处理函数绑定this
class Button {
constructor() {
this.text = 'Click me';
// 使用bind保持this指向
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
console.log(this.text);
}
}
13. TypeScript装饰器
装饰器类型
// 类装饰器
function ClassDecorator(constructor: Function) {
console.log('类装饰器执行');
constructor.prototype.newProperty = 'added by decorator';
}
// 方法装饰器
function MethodDecorator(
target: any,
propertyKey: string,
descriptor: PropertyDescriptor
) {
console.log(`方法装饰器:${propertyKey}`);
const originalMethod = descriptor.value;
descriptor.value = function(...args: any[]) {
console.log(`调用方法:${propertyKey}`);
return originalMethod.apply(this, args);
};
}
// 属性装饰器
function PropertyDecorator(target: any, propertyKey: string) {
console.log(`属性装饰器:${propertyKey}`);
}
// 参数装饰器
function ParameterDecorator(
target: any,
propertyKey: string,
parameterIndex: number
) {
console.log(`参数装饰器:${propertyKey}的第${parameterIndex}个参数`);
}
// 访问器装饰器
function AccessorDecorator(
target: any,
propertyKey: string,
descriptor: PropertyDescriptor
) {
console.log(`访问器装饰器:${propertyKey}`);
}
// 装饰器工厂
function LogDecorator(message: string) {
return function(target: any, propertyKey: string, descriptor?: PropertyDescriptor) {
console.log(`${message}: ${propertyKey}`);
};
}
实际应用示例
// 1. 日志装饰器
function log(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
const originalMethod = descriptor.value;
descriptor.value = function(...args: any[]) {
console.log(`调用 ${propertyKey},参数:`, args);
const result = originalMethod.apply(this, args);
console.log(`返回结果:`, result);
return result;
};
}
// 2. 自动绑定this装饰器
function autobind(
_target: any,
_propertyKey: string,
descriptor: PropertyDescriptor
) {
const originalMethod = descriptor.value;
const adjustedDescriptor: PropertyDescriptor = {
configurable: true,
enumerable: false,
get() {
// 返回绑定this的方法
return originalMethod.bind(this);
}
};
return adjustedDescriptor;
}
// 3. 验证装饰器
function validate(
target: any,
propertyKey: string,
descriptor: PropertyDescriptor
) {
const originalMethod = descriptor.value;
descriptor.value = function(...args: any[]) {
// 参数验证逻辑
args.forEach((arg, index) => {
if (arg === undefined || arg === null) {
throw new Error(`参数 ${index} 不能为空`);
}
});
return originalMethod.apply(this, args);
};
}
// 使用示例
class UserService {
private users: string[] = [];
@log
@validate
addUser(@ParameterDecorator name: string) {
this.users.push(name);
return this.users;
}
@autobind
getUsers() {
return this.users;
}
}
14. 10w数据展示优化
虚拟列表实现
时间分片渲染
// 使用requestAnimationFrame分批渲染
function renderLargeData(data, container, chunkSize = 100) {
let index = 0;
function renderChunk() {
const fragment = document.createDocumentFragment();
for (let i = 0; i < chunkSize && index < data.length; i++, index++) {
const item = document.createElement('div');
item.textContent = data[index];
fragment.appendChild(item);
}
container.appendChild(fragment);
// 如果还有数据,继续渲染下一批
if (index < data.length) {
requestAnimationFrame(renderChunk);
}
}
renderChunk();
}
// 使用Web Worker处理数据
const worker = new Worker('data-processor.js');
worker.postMessage({ action: 'process', data: largeData });
worker.onmessage = function(event) {
const processedData = event.data;
// 在主线程渲染处理后的数据
};
15. 时间切片
基本原理
// 使用requestIdleCallback实现时间切片
function timeSlicingWork(unitsOfWork) {
let currentIndex = 0;
function doWork(deadline) {
// 在空闲时间内执行工作单元
while (currentIndex < unitsOfWork.length && deadline.timeRemaining() > 0) {
performUnitOfWork(unitsOfWork[currentIndex]);
currentIndex++;
}
// 如果还有工作,继续调度
if (currentIndex < unitsOfWork.length) {
requestIdleCallback(doWork);
} else {
console.log('所有工作完成');
}
}
requestIdleCallback(doWork);
}
// React中的时间切片实现(简化版)
function workLoop(deadline) {
let shouldYield = false;
while (nextUnitOfWork && !shouldYield) {
// 执行工作单元
nextUnitOfWork = performUnitOfWork(nextUnitOfWork);
// 检查是否需要让出控制权
shouldYield = deadline.timeRemaining() < 1;
}
// 如果还有工作,继续调度
if (nextUnitOfWork) {
requestIdleCallback(workLoop);
}
}
requestIdleCallback(workLoop);
实际应用示例
// 1. 大数据处理
function processBigData(data, processItem, chunkSize = 100) {
return new Promise((resolve) => {
let index = 0;
const results = [];
function processChunk(deadline) {
while (index < data.length && deadline.timeRemaining() > 0) {
const chunk = data.slice(index, index + chunkSize);
// 处理数据块
for (const item of chunk) {
results.push(processItem(item));
}
index += chunkSize;
// 更新进度
updateProgress((index / data.length) * 100);
}
if (index < data.length) {
// 还有数据,继续处理
requestIdleCallback(processChunk);
} else {
// 处理完成
resolve(results);
}
}
requestIdleCallback(processChunk);
});
}
// 2. 长列表渲染优化
class VirtualScroller {
constructor(container, items, renderItem) {
this.container = container;
this.items = items;
this.renderItem = renderItem;
this.renderedItems = new Set();
}
renderVisibleItems() {
const visibleRange = this.getVisibleRange();
const itemsToRender = [];
for (let i = visibleRange.start; i < visibleRange.end; i++) {
if (!this.renderedItems.has(i)) {
itemsToRender.push(i);
}
}
// 使用时间切片分批渲染
this.renderWithTimeSlice(itemsToRender);
}
renderWithTimeSlice(itemIndices) {
let index = 0;
const renderBatch = (deadline) => {
while (index < itemIndices.length && deadline.timeRemaining() > 0) {
const itemIndex = itemIndices[index];
const item = this.items[itemIndex];
// 渲染单个项目
const element = this.renderItem(item, itemIndex);
this.container.appendChild(element);
this.renderedItems.add(itemIndex);
index++;
}
if (index < itemIndices.length) {
requestIdleCallback(renderBatch);
}
};
requestIdleCallback(renderBatch);
}
}
React Concurrent Mode中的时间切片
// React 18+中的并发特性
import { startTransition, useDeferredValue } from 'react';
function SearchResults({ query }) {
const deferredQuery = useDeferredValue(query);
return (
);
}
// 在事件处理中使用startTransition
function handleChange(e) {
setInput(e.target.value);
// 将setQuery标记为过渡更新
startTransition(() => {
setQuery(e.target.value);
});
}
// 这会告诉React这个更新不是紧急的,可以被中断
最后,欢迎对前端岗位是否会被AI取代投票。如觉得面试题有用,评论区留言,会继续更新 小中大厂常见精选面试题。