字节最新Web前端面试八股100问7天刷完祝你冲击大厂offer薪资暴涨50%最近很多前端开发者都在准备大厂面试特别是字节跳动这类一线互联网公司的前端岗位。作为面试过多个大厂的前端开发者我整理了一份最新的Web前端面试八股文100问涵盖了HTML、CSS、JavaScript、Vue、React、Webpack、性能优化等核心知识点。无论你是准备校招还是社招这套题库都能帮你系统复习前端知识体系。1. HTML基础与语义化1.1 HTML5新特性与语义化标签HTML5带来了很多实用的新特性面试中经常被问到。语义化标签不仅让代码更易读还能提升SEO效果和可访问性。!DOCTYPE html html langzh-CN head meta charsetUTF-8 meta nameviewport contentwidthdevice-width, initial-scale1.0 title语义化示例/title /head body header nav ul lia href#home首页/a/li lia href#about关于/a/li /ul /nav /header main article h1文章标题/h1 section p文章内容段落.../p /section /article aside h2相关推荐/h2 /aside /main footer p版权信息/p /footer /body /html常见面试问题说说HTML5有哪些新特性为什么要使用语义化标签section和article的区别是什么如何理解HTML的可访问性1.2 表单与输入类型HTML5为表单引入了很多新的输入类型和属性大大提升了用户体验。form !-- 新的输入类型 -- input typeemail placeholder请输入邮箱 required input typeurl placeholder请输入网址 input typenumber min1 max100 step1 input typedate input typecolor !-- 新的表单属性 -- input typetext placeholder请输入内容 autofocus input typetext pattern[A-Za-z]{3} datalist idbrowsers option valueChrome option valueFirefox /datalist /form2. CSS核心概念与布局2.1 盒模型与定位理解盒模型是CSS布局的基础不同的盒模型会影响元素的尺寸计算。/* 标准盒模型 */ .box-standard { box-sizing: content-box; width: 200px; padding: 20px; border: 5px solid #ccc; /* 总宽度 200 20*2 5*2 250px */ } /* 怪异盒模型 */ .box-border { box-sizing: border-box; width: 200px; padding: 20px; border: 5px solid #ccc; /* 总宽度 200px */ } /* 定位方式 */ .position-relative { position: relative; top: 10px; left: 20px; } .position-absolute { position: absolute; top: 0; right: 0; } .position-fixed { position: fixed; bottom: 20px; right: 20px; } .position-sticky { position: sticky; top: 0; }2.2 Flex布局实战Flex布局是现代Web开发中最常用的布局方式之一需要熟练掌握。.container { display: flex; flex-direction: row; /* 主轴方向 */ justify-content: space-between; /* 主轴对齐 */ align-items: center; /* 交叉轴对齐 */ flex-wrap: wrap; /* 换行 */ gap: 10px; /* 项目间距 */ } .item { flex: 1; /* 弹性比例 */ min-width: 200px; } .item-large { flex: 2; /* 占据两倍空间 */ } /* 响应式Flex布局 */ media (max-width: 768px) { .container { flex-direction: column; } }2.3 Grid网格布局Grid布局适合复杂的二维布局场景比Flex更适合整体页面布局。.grid-container { display: grid; grid-template-columns: 1fr 2fr 1fr; /* 三列布局 */ grid-template-rows: 100px auto 100px; grid-template-areas: header header header sidebar main aside footer footer footer; gap: 20px; } .header { grid-area: header; } .sidebar { grid-area: sidebar; } .main { grid-area: main; } .aside { grid-area: aside; } .footer { grid-area: footer; } /* 响应式Grid */ media (max-width: 768px) { .grid-container { grid-template-columns: 1fr; grid-template-areas: header sidebar main aside footer; } }3. JavaScript核心知识3.1 变量作用域与闭包理解作用域链和闭包是JavaScript高级开发的必备知识。// 变量提升 console.log(a); // undefined var a 10; // let/const 暂时性死区 // console.log(b); // ReferenceError let b 20; // 闭包示例 function createCounter() { let count 0; return function() { count; return count; }; } const counter createCounter(); console.log(counter()); // 1 console.log(counter()); // 2 // 模块模式 const module (function() { let privateVar 0; return { increment: function() { privateVar; }, getValue: function() { return privateVar; } }; })();3.2 原型与继承JavaScript基于原型的继承机制是面试高频考点。// 构造函数 function Person(name, age) { this.name name; this.age age; } // 原型方法 Person.prototype.sayHello function() { console.log(Hello, Im ${this.name}); }; // 继承 function Student(name, age, grade) { Person.call(this, name, age); this.grade grade; } // 设置原型链 Student.prototype Object.create(Person.prototype); Student.prototype.constructor Student; // ES6 Class class Animal { constructor(name) { this.name name; } speak() { console.log(${this.name} makes a noise.); } } class Dog extends Animal { constructor(name, breed) { super(name); this.breed breed; } speak() { console.log(${this.name} barks.); } }3.3 异步编程Promise、async/await是现代JavaScript异步编程的核心。// Promise基础 function fetchData() { return new Promise((resolve, reject) { setTimeout(() { Math.random() 0.5 ? resolve(数据获取成功) : reject(获取失败); }, 1000); }); } // Promise链式调用 fetchData() .then(data { console.log(data); return data processed; }) .then(processedData { console.log(processedData); }) .catch(error { console.error(Error:, error); }); // async/await async function processData() { try { const data await fetchData(); console.log(Async:, data); return data; } catch (error) { console.error(Async Error:, error); throw error; } } // Promise.all 并行处理 async function parallelTasks() { const [result1, result2] await Promise.all([ fetchData(), fetchData() ]); console.log(并行结果:, result1, result2); }4. Vue.js框架深度解析4.1 Vue响应式原理理解Vue的响应式系统是掌握Vue框架的关键。// 简易响应式实现 class Dep { constructor() { this.subscribers new Set(); } depend() { if (activeEffect) { this.subscribers.add(activeEffect); } } notify() { this.subscribers.forEach(effect effect()); } } let activeEffect null; function watchEffect(effect) { activeEffect effect; effect(); activeEffect null; } // 使用Proxy实现响应式 function reactive(obj) { const deps {}; return new Proxy(obj, { get(target, key) { if (!deps[key]) { deps[key] new Dep(); } deps[key].depend(); return target[key]; }, set(target, key, value) { target[key] value; if (deps[key]) { deps[key].notify(); } return true; } }); }4.2 Vue组件通信组件通信是Vue应用开发中的常见需求。// 父子组件通信 // 父组件 Vue.component(parent-component, { template: div child-component :messageparentMessage child-eventhandleChildEvent / /div , data() { return { parentMessage: 来自父组件的消息 }; }, methods: { handleChildEvent(data) { console.log(子组件触发的事件:, data); } } }); // 子组件 Vue.component(child-component, { props: [message], template: div p{{ message }}/p button clicksendToParent通知父组件/button /div , methods: { sendToParent() { this.$emit(child-event, { data: 子组件数据 }); } } }); // Vuex状态管理 const store new Vuex.Store({ state: { count: 0 }, mutations: { increment(state) { state.count; } }, actions: { asyncIncrement({ commit }) { setTimeout(() { commit(increment); }, 1000); } }, getters: { doubleCount: state state.count * 2 } });4.3 Vue 3 Composition APIVue 3的Composition API提供了更灵活的代码组织方式。import { ref, reactive, computed, watch, onMounted } from vue; export default { setup() { // 响应式数据 const count ref(0); const state reactive({ name: Vue 3, version: 3.0 }); // 计算属性 const doubleCount computed(() count.value * 2); // 监听器 watch(count, (newVal, oldVal) { console.log(count从${oldVal}变为${newVal}); }); // 生命周期 onMounted(() { console.log(组件已挂载); }); // 方法 const increment () { count.value; }; return { count, state, doubleCount, increment }; } };5. React框架核心概念5.1 Hooks深度使用Hooks是React函数组件的核心特性。import React, { useState, useEffect, useCallback, useMemo, useRef } from react; function ExampleComponent() { // useState const [count, setCount] useState(0); const [data, setData] useState([]); // useRef const inputRef useRef(null); // useMemo - 缓存计算结果 const expensiveValue useMemo(() { return count * 1000; }, [count]); // useCallback - 缓存函数 const handleClick useCallback(() { setCount(prev prev 1); }, []); // useEffect - 副作用处理 useEffect(() { // 组件挂载时执行 console.log(Component mounted); inputRef.current?.focus(); // 清理函数 return () { console.log(Component will unmount); }; }, []); useEffect(() { // 依赖count的变化 document.title Count: ${count}; }, [count]); return ( div input ref{inputRef} / pCount: {count}/p pExpensive: {expensiveValue}/p button onClick{handleClick}Increment/button /div ); }5.2 状态管理与Context APIReact的状态管理方案选择是面试常见话题。// Context API const ThemeContext React.createContext(); function App() { const [theme, setTheme] useState(light); return ( ThemeContext.Provider value{{ theme, setTheme }} Toolbar / /ThemeContext.Provider ); } function Toolbar() { return ( div ThemedButton / /div ); } function ThemedButton() { const { theme, setTheme } useContext(ThemeContext); return ( button style{{ background: theme light ? #fff : #333, color: theme light ? #000 : #fff }} onClick{() setTheme(theme light ? dark : light)} Toggle Theme /button ); } // 自定义Hook function useLocalStorage(key, initialValue) { const [storedValue, setStoredValue] useState(() { try { const item window.localStorage.getItem(key); return item ? JSON.parse(item) : initialValue; } catch (error) { return initialValue; } }); const setValue (value) { try { setStoredValue(value); window.localStorage.setItem(key, JSON.stringify(value)); } catch (error) { console.error(error); } }; return [storedValue, setValue]; }6. Webpack构建优化6.1 配置优化与代码分割Webpack配置优化直接影响应用性能。// webpack.config.js const path require(path); const { BundleAnalyzerPlugin } require(webpack-bundle-analyzer); module.exports { mode: production, entry: { main: ./src/index.js, vendor: ./src/vendor.js }, output: { path: path.resolve(__dirname, dist), filename: [name].[contenthash].js, clean: true }, optimization: { splitChunks: { chunks: all, cacheGroups: { vendor: { test: /[\\/]node_modules[\\/]/, name: vendors, chunks: all, }, common: { minChunks: 2, name: common, chunks: all, minSize: 0 } } }, runtimeChunk: single }, module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: { loader: babel-loader, options: { presets: [babel/preset-env] } } }, { test: /\.css$/, use: [style-loader, css-loader] } ] }, plugins: [ new BundleAnalyzerPlugin({ analyzerMode: static, openAnalyzer: false }) ] };6.2 性能优化策略构建性能优化是大型项目的关键。// 开发环境配置 module.exports { mode: development, devtool: eval-source-map, devServer: { contentBase: ./dist, hot: true, port: 3000, historyApiFallback: true }, module: { rules: [ { test: /\.js$/, enforce: pre, use: [source-map-loader] } ] } }; // 生产环境优化 const TerserPlugin require(terser-webpack-plugin); const CssMinimizerPlugin require(css-minimizer-webpack-plugin); module.exports { optimization: { minimizer: [ new TerserPlugin({ parallel: true, terserOptions: { compress: { drop_console: true } } }), new CssMinimizerPlugin() ] }, performance: { hints: warning, maxEntrypointSize: 512000, maxAssetSize: 512000 } };7. 浏览器原理与性能优化7.1 渲染原理与重绘重排理解浏览器渲染机制是性能优化的基础。// 避免强制同步布局 function badExample() { // 不好的写法引起强制同步布局 const element document.getElementById(myElement); element.style.width 100px; const width element.offsetWidth; // 强制布局计算 element.style.height width px; } function goodExample() { // 好的写法批量读写 const element document.getElementById(myElement); const width element.offsetWidth; // 使用requestAnimationFrame批量更新 requestAnimationFrame(() { element.style.width 100px; element.style.height width px; }); } // 使用DocumentFragment批量操作DOM function efficientDOMUpdate() { const fragment document.createDocumentFragment(); for (let i 0; i 1000; i) { const div document.createElement(div); div.textContent Item ${i}; fragment.appendChild(div); } document.getElementById(container).appendChild(fragment); }7.2 内存管理与性能监控内存泄漏是前端应用的常见问题。// 内存泄漏示例 function createLeak() { const elements []; return function() { const element document.createElement(div); document.body.appendChild(element); elements.push(element); // 闭包引用导致内存泄漏 element.onclick function() { console.log(elements.length); }; }; } // 正确的写法 function noLeak() { return function() { const element document.createElement(div); document.body.appendChild(element); // 避免闭包引用大对象 element.onclick function() { console.log(clicked); }; // 及时清理 return () { element.remove(); }; }; } // 性能监控 class PerformanceMonitor { constructor() { this.metrics {}; } startMeasure(name) { this.metrics[name] { start: performance.now() }; } endMeasure(name) { if (this.metrics[name]) { this.metrics[name].end performance.now(); this.metrics[name].duration this.metrics[name].end - this.metrics[name].start; } } report() { console.table(this.metrics); } }8. 网络请求与安全8.1 HTTP协议与缓存策略理解HTTP协议是前端开发的基础。// Fetch API使用 class ApiService { constructor(baseURL) { this.baseURL baseURL; this.defaultOptions { headers: { Content-Type: application/json } }; } async request(endpoint, options {}) { const url ${this.baseURL}${endpoint}; const config { ...this.defaultOptions, ...options }; try { const response await fetch(url, config); if (!response.ok) { throw new Error(HTTP error! status: ${response.status}); } const data await response.json(); return data; } catch (error) { console.error(API请求失败:, error); throw error; } } // 缓存策略实现 async getWithCache(endpoint, cacheKey, ttl 300000) { // 5分钟缓存 const cached localStorage.getItem(cacheKey); const now Date.now(); if (cached) { const { data, timestamp } JSON.parse(cached); if (now - timestamp ttl) { return data; } } const freshData await this.request(endpoint); localStorage.setItem(cacheKey, JSON.stringify({ data: freshData, timestamp: now })); return freshData; } }8.2 安全防护实践Web安全是前端开发必须重视的方面。// XSS防护 function sanitizeHTML(str) { const div document.createElement(div); div.textContent str; return div.innerHTML; } // CSRF防护 class CSRFProtection { static getToken() { let token localStorage.getItem(csrf_token); if (!token) { token this.generateToken(); localStorage.setItem(csrf_token, token); } return token; } static generateToken() { return Math.random().toString(36).substring(2) Date.now().toString(36); } static validateToken(token) { const storedToken localStorage.getItem(csrf_token); return token storedToken; } } // 安全的HTTP头设置 const securityHeaders { Content-Security-Policy: default-src self, X-Content-Type-Options: nosniff, X-Frame-Options: DENY, X-XSS-Protection: 1; modeblock };9. 工程化与工具链9.1 现代化前端工作流完整的前端工程化流程包含多个环节。// ESLint配置 module.exports { env: { browser: true, es2021: true }, extends: [ eslint:recommended, vue/eslint-config-standard ], parserOptions: { ecmaVersion: 12, sourceType: module }, rules: { no-console: process.env.NODE_ENV production ? warn : off, no-debugger: process.env.NODE_ENV production ? warn : off, indent: [error, 4], quotes: [error, single] } }; // Prettier配置 { semi: true, trailingComma: none, singleQuote: true, printWidth: 80, tabWidth: 4 } // Git Hooks配置 (package.json) { scripts: { pre-commit: lint-staged, pre-push: npm run test }, lint-staged: { *.{js,vue}: [ eslint --fix, prettier --write ] } }9.2 测试策略完整的测试体系保证代码质量。// Jest单元测试 describe(Math operations, () { test(adds 1 2 to equal 3, () { expect(1 2).toBe(3); }); test(async operation, async () { const result await fetchData(); expect(result).toBe(expected data); }); }); // Vue组件测试 import { shallowMount } from vue/test-utils; import MyComponent from /components/MyComponent.vue; describe(MyComponent, () { it(renders correctly, () { const wrapper shallowMount(MyComponent, { propsData: { message: test } }); expect(wrapper.text()).toMatch(test); }); }); // E2E测试 (Cypress) describe(User journey, () { it(completes user registration, () { cy.visit(/register); cy.get([data-testidemail]).type(testexample.com); cy.get([data-testidpassword]).type(password123); cy.get([data-testidsubmit]).click(); cy.url().should(include, /dashboard); }); });10. 面试技巧与准备策略10.1 技术面试准备技术面试需要系统性的准备和练习。算法准备重点数组、字符串操作链表相关题目树结构的遍历和操作动态规划基础排序和搜索算法// 常见的算法题解法 function twoSum(nums, target) { const map new Map(); for (let i 0; i nums.length; i) { const complement target - nums[i]; if (map.has(complement)) { return [map.get(complement), i]; } map.set(nums[i], i); } return []; } // 二叉树遍历 class TreeNode { constructor(val) { this.val val; this.left this.right null; } } function inorderTraversal(root) { const result []; function traverse(node) { if (!node) return; traverse(node.left); result.push(node.val); traverse(node.right); } traverse(root); return result; }10.2 项目经验梳理如何有效展示项目经验是面试成功的关键。STAR法则描述项目Situation项目背景和业务需求Task你的具体职责和任务Action采取的技术方案和实现过程Result达成的成果和量化指标技术深度展示架构设计思路和权衡性能优化具体措施遇到的挑战和解决方案代码质量和工程化实践通过系统学习这100个前端面试核心问题结合实际项目练习你就能在字节等大厂前端面试中游刃有余。记住技术深度和解决问题的能力比死记硬背更重要理解原理并能灵活应用才是面试官最看重的素质。
Web前端面试核心知识点全解析:HTML5到性能优化
字节最新Web前端面试八股100问7天刷完祝你冲击大厂offer薪资暴涨50%最近很多前端开发者都在准备大厂面试特别是字节跳动这类一线互联网公司的前端岗位。作为面试过多个大厂的前端开发者我整理了一份最新的Web前端面试八股文100问涵盖了HTML、CSS、JavaScript、Vue、React、Webpack、性能优化等核心知识点。无论你是准备校招还是社招这套题库都能帮你系统复习前端知识体系。1. HTML基础与语义化1.1 HTML5新特性与语义化标签HTML5带来了很多实用的新特性面试中经常被问到。语义化标签不仅让代码更易读还能提升SEO效果和可访问性。!DOCTYPE html html langzh-CN head meta charsetUTF-8 meta nameviewport contentwidthdevice-width, initial-scale1.0 title语义化示例/title /head body header nav ul lia href#home首页/a/li lia href#about关于/a/li /ul /nav /header main article h1文章标题/h1 section p文章内容段落.../p /section /article aside h2相关推荐/h2 /aside /main footer p版权信息/p /footer /body /html常见面试问题说说HTML5有哪些新特性为什么要使用语义化标签section和article的区别是什么如何理解HTML的可访问性1.2 表单与输入类型HTML5为表单引入了很多新的输入类型和属性大大提升了用户体验。form !-- 新的输入类型 -- input typeemail placeholder请输入邮箱 required input typeurl placeholder请输入网址 input typenumber min1 max100 step1 input typedate input typecolor !-- 新的表单属性 -- input typetext placeholder请输入内容 autofocus input typetext pattern[A-Za-z]{3} datalist idbrowsers option valueChrome option valueFirefox /datalist /form2. CSS核心概念与布局2.1 盒模型与定位理解盒模型是CSS布局的基础不同的盒模型会影响元素的尺寸计算。/* 标准盒模型 */ .box-standard { box-sizing: content-box; width: 200px; padding: 20px; border: 5px solid #ccc; /* 总宽度 200 20*2 5*2 250px */ } /* 怪异盒模型 */ .box-border { box-sizing: border-box; width: 200px; padding: 20px; border: 5px solid #ccc; /* 总宽度 200px */ } /* 定位方式 */ .position-relative { position: relative; top: 10px; left: 20px; } .position-absolute { position: absolute; top: 0; right: 0; } .position-fixed { position: fixed; bottom: 20px; right: 20px; } .position-sticky { position: sticky; top: 0; }2.2 Flex布局实战Flex布局是现代Web开发中最常用的布局方式之一需要熟练掌握。.container { display: flex; flex-direction: row; /* 主轴方向 */ justify-content: space-between; /* 主轴对齐 */ align-items: center; /* 交叉轴对齐 */ flex-wrap: wrap; /* 换行 */ gap: 10px; /* 项目间距 */ } .item { flex: 1; /* 弹性比例 */ min-width: 200px; } .item-large { flex: 2; /* 占据两倍空间 */ } /* 响应式Flex布局 */ media (max-width: 768px) { .container { flex-direction: column; } }2.3 Grid网格布局Grid布局适合复杂的二维布局场景比Flex更适合整体页面布局。.grid-container { display: grid; grid-template-columns: 1fr 2fr 1fr; /* 三列布局 */ grid-template-rows: 100px auto 100px; grid-template-areas: header header header sidebar main aside footer footer footer; gap: 20px; } .header { grid-area: header; } .sidebar { grid-area: sidebar; } .main { grid-area: main; } .aside { grid-area: aside; } .footer { grid-area: footer; } /* 响应式Grid */ media (max-width: 768px) { .grid-container { grid-template-columns: 1fr; grid-template-areas: header sidebar main aside footer; } }3. JavaScript核心知识3.1 变量作用域与闭包理解作用域链和闭包是JavaScript高级开发的必备知识。// 变量提升 console.log(a); // undefined var a 10; // let/const 暂时性死区 // console.log(b); // ReferenceError let b 20; // 闭包示例 function createCounter() { let count 0; return function() { count; return count; }; } const counter createCounter(); console.log(counter()); // 1 console.log(counter()); // 2 // 模块模式 const module (function() { let privateVar 0; return { increment: function() { privateVar; }, getValue: function() { return privateVar; } }; })();3.2 原型与继承JavaScript基于原型的继承机制是面试高频考点。// 构造函数 function Person(name, age) { this.name name; this.age age; } // 原型方法 Person.prototype.sayHello function() { console.log(Hello, Im ${this.name}); }; // 继承 function Student(name, age, grade) { Person.call(this, name, age); this.grade grade; } // 设置原型链 Student.prototype Object.create(Person.prototype); Student.prototype.constructor Student; // ES6 Class class Animal { constructor(name) { this.name name; } speak() { console.log(${this.name} makes a noise.); } } class Dog extends Animal { constructor(name, breed) { super(name); this.breed breed; } speak() { console.log(${this.name} barks.); } }3.3 异步编程Promise、async/await是现代JavaScript异步编程的核心。// Promise基础 function fetchData() { return new Promise((resolve, reject) { setTimeout(() { Math.random() 0.5 ? resolve(数据获取成功) : reject(获取失败); }, 1000); }); } // Promise链式调用 fetchData() .then(data { console.log(data); return data processed; }) .then(processedData { console.log(processedData); }) .catch(error { console.error(Error:, error); }); // async/await async function processData() { try { const data await fetchData(); console.log(Async:, data); return data; } catch (error) { console.error(Async Error:, error); throw error; } } // Promise.all 并行处理 async function parallelTasks() { const [result1, result2] await Promise.all([ fetchData(), fetchData() ]); console.log(并行结果:, result1, result2); }4. Vue.js框架深度解析4.1 Vue响应式原理理解Vue的响应式系统是掌握Vue框架的关键。// 简易响应式实现 class Dep { constructor() { this.subscribers new Set(); } depend() { if (activeEffect) { this.subscribers.add(activeEffect); } } notify() { this.subscribers.forEach(effect effect()); } } let activeEffect null; function watchEffect(effect) { activeEffect effect; effect(); activeEffect null; } // 使用Proxy实现响应式 function reactive(obj) { const deps {}; return new Proxy(obj, { get(target, key) { if (!deps[key]) { deps[key] new Dep(); } deps[key].depend(); return target[key]; }, set(target, key, value) { target[key] value; if (deps[key]) { deps[key].notify(); } return true; } }); }4.2 Vue组件通信组件通信是Vue应用开发中的常见需求。// 父子组件通信 // 父组件 Vue.component(parent-component, { template: div child-component :messageparentMessage child-eventhandleChildEvent / /div , data() { return { parentMessage: 来自父组件的消息 }; }, methods: { handleChildEvent(data) { console.log(子组件触发的事件:, data); } } }); // 子组件 Vue.component(child-component, { props: [message], template: div p{{ message }}/p button clicksendToParent通知父组件/button /div , methods: { sendToParent() { this.$emit(child-event, { data: 子组件数据 }); } } }); // Vuex状态管理 const store new Vuex.Store({ state: { count: 0 }, mutations: { increment(state) { state.count; } }, actions: { asyncIncrement({ commit }) { setTimeout(() { commit(increment); }, 1000); } }, getters: { doubleCount: state state.count * 2 } });4.3 Vue 3 Composition APIVue 3的Composition API提供了更灵活的代码组织方式。import { ref, reactive, computed, watch, onMounted } from vue; export default { setup() { // 响应式数据 const count ref(0); const state reactive({ name: Vue 3, version: 3.0 }); // 计算属性 const doubleCount computed(() count.value * 2); // 监听器 watch(count, (newVal, oldVal) { console.log(count从${oldVal}变为${newVal}); }); // 生命周期 onMounted(() { console.log(组件已挂载); }); // 方法 const increment () { count.value; }; return { count, state, doubleCount, increment }; } };5. React框架核心概念5.1 Hooks深度使用Hooks是React函数组件的核心特性。import React, { useState, useEffect, useCallback, useMemo, useRef } from react; function ExampleComponent() { // useState const [count, setCount] useState(0); const [data, setData] useState([]); // useRef const inputRef useRef(null); // useMemo - 缓存计算结果 const expensiveValue useMemo(() { return count * 1000; }, [count]); // useCallback - 缓存函数 const handleClick useCallback(() { setCount(prev prev 1); }, []); // useEffect - 副作用处理 useEffect(() { // 组件挂载时执行 console.log(Component mounted); inputRef.current?.focus(); // 清理函数 return () { console.log(Component will unmount); }; }, []); useEffect(() { // 依赖count的变化 document.title Count: ${count}; }, [count]); return ( div input ref{inputRef} / pCount: {count}/p pExpensive: {expensiveValue}/p button onClick{handleClick}Increment/button /div ); }5.2 状态管理与Context APIReact的状态管理方案选择是面试常见话题。// Context API const ThemeContext React.createContext(); function App() { const [theme, setTheme] useState(light); return ( ThemeContext.Provider value{{ theme, setTheme }} Toolbar / /ThemeContext.Provider ); } function Toolbar() { return ( div ThemedButton / /div ); } function ThemedButton() { const { theme, setTheme } useContext(ThemeContext); return ( button style{{ background: theme light ? #fff : #333, color: theme light ? #000 : #fff }} onClick{() setTheme(theme light ? dark : light)} Toggle Theme /button ); } // 自定义Hook function useLocalStorage(key, initialValue) { const [storedValue, setStoredValue] useState(() { try { const item window.localStorage.getItem(key); return item ? JSON.parse(item) : initialValue; } catch (error) { return initialValue; } }); const setValue (value) { try { setStoredValue(value); window.localStorage.setItem(key, JSON.stringify(value)); } catch (error) { console.error(error); } }; return [storedValue, setValue]; }6. Webpack构建优化6.1 配置优化与代码分割Webpack配置优化直接影响应用性能。// webpack.config.js const path require(path); const { BundleAnalyzerPlugin } require(webpack-bundle-analyzer); module.exports { mode: production, entry: { main: ./src/index.js, vendor: ./src/vendor.js }, output: { path: path.resolve(__dirname, dist), filename: [name].[contenthash].js, clean: true }, optimization: { splitChunks: { chunks: all, cacheGroups: { vendor: { test: /[\\/]node_modules[\\/]/, name: vendors, chunks: all, }, common: { minChunks: 2, name: common, chunks: all, minSize: 0 } } }, runtimeChunk: single }, module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: { loader: babel-loader, options: { presets: [babel/preset-env] } } }, { test: /\.css$/, use: [style-loader, css-loader] } ] }, plugins: [ new BundleAnalyzerPlugin({ analyzerMode: static, openAnalyzer: false }) ] };6.2 性能优化策略构建性能优化是大型项目的关键。// 开发环境配置 module.exports { mode: development, devtool: eval-source-map, devServer: { contentBase: ./dist, hot: true, port: 3000, historyApiFallback: true }, module: { rules: [ { test: /\.js$/, enforce: pre, use: [source-map-loader] } ] } }; // 生产环境优化 const TerserPlugin require(terser-webpack-plugin); const CssMinimizerPlugin require(css-minimizer-webpack-plugin); module.exports { optimization: { minimizer: [ new TerserPlugin({ parallel: true, terserOptions: { compress: { drop_console: true } } }), new CssMinimizerPlugin() ] }, performance: { hints: warning, maxEntrypointSize: 512000, maxAssetSize: 512000 } };7. 浏览器原理与性能优化7.1 渲染原理与重绘重排理解浏览器渲染机制是性能优化的基础。// 避免强制同步布局 function badExample() { // 不好的写法引起强制同步布局 const element document.getElementById(myElement); element.style.width 100px; const width element.offsetWidth; // 强制布局计算 element.style.height width px; } function goodExample() { // 好的写法批量读写 const element document.getElementById(myElement); const width element.offsetWidth; // 使用requestAnimationFrame批量更新 requestAnimationFrame(() { element.style.width 100px; element.style.height width px; }); } // 使用DocumentFragment批量操作DOM function efficientDOMUpdate() { const fragment document.createDocumentFragment(); for (let i 0; i 1000; i) { const div document.createElement(div); div.textContent Item ${i}; fragment.appendChild(div); } document.getElementById(container).appendChild(fragment); }7.2 内存管理与性能监控内存泄漏是前端应用的常见问题。// 内存泄漏示例 function createLeak() { const elements []; return function() { const element document.createElement(div); document.body.appendChild(element); elements.push(element); // 闭包引用导致内存泄漏 element.onclick function() { console.log(elements.length); }; }; } // 正确的写法 function noLeak() { return function() { const element document.createElement(div); document.body.appendChild(element); // 避免闭包引用大对象 element.onclick function() { console.log(clicked); }; // 及时清理 return () { element.remove(); }; }; } // 性能监控 class PerformanceMonitor { constructor() { this.metrics {}; } startMeasure(name) { this.metrics[name] { start: performance.now() }; } endMeasure(name) { if (this.metrics[name]) { this.metrics[name].end performance.now(); this.metrics[name].duration this.metrics[name].end - this.metrics[name].start; } } report() { console.table(this.metrics); } }8. 网络请求与安全8.1 HTTP协议与缓存策略理解HTTP协议是前端开发的基础。// Fetch API使用 class ApiService { constructor(baseURL) { this.baseURL baseURL; this.defaultOptions { headers: { Content-Type: application/json } }; } async request(endpoint, options {}) { const url ${this.baseURL}${endpoint}; const config { ...this.defaultOptions, ...options }; try { const response await fetch(url, config); if (!response.ok) { throw new Error(HTTP error! status: ${response.status}); } const data await response.json(); return data; } catch (error) { console.error(API请求失败:, error); throw error; } } // 缓存策略实现 async getWithCache(endpoint, cacheKey, ttl 300000) { // 5分钟缓存 const cached localStorage.getItem(cacheKey); const now Date.now(); if (cached) { const { data, timestamp } JSON.parse(cached); if (now - timestamp ttl) { return data; } } const freshData await this.request(endpoint); localStorage.setItem(cacheKey, JSON.stringify({ data: freshData, timestamp: now })); return freshData; } }8.2 安全防护实践Web安全是前端开发必须重视的方面。// XSS防护 function sanitizeHTML(str) { const div document.createElement(div); div.textContent str; return div.innerHTML; } // CSRF防护 class CSRFProtection { static getToken() { let token localStorage.getItem(csrf_token); if (!token) { token this.generateToken(); localStorage.setItem(csrf_token, token); } return token; } static generateToken() { return Math.random().toString(36).substring(2) Date.now().toString(36); } static validateToken(token) { const storedToken localStorage.getItem(csrf_token); return token storedToken; } } // 安全的HTTP头设置 const securityHeaders { Content-Security-Policy: default-src self, X-Content-Type-Options: nosniff, X-Frame-Options: DENY, X-XSS-Protection: 1; modeblock };9. 工程化与工具链9.1 现代化前端工作流完整的前端工程化流程包含多个环节。// ESLint配置 module.exports { env: { browser: true, es2021: true }, extends: [ eslint:recommended, vue/eslint-config-standard ], parserOptions: { ecmaVersion: 12, sourceType: module }, rules: { no-console: process.env.NODE_ENV production ? warn : off, no-debugger: process.env.NODE_ENV production ? warn : off, indent: [error, 4], quotes: [error, single] } }; // Prettier配置 { semi: true, trailingComma: none, singleQuote: true, printWidth: 80, tabWidth: 4 } // Git Hooks配置 (package.json) { scripts: { pre-commit: lint-staged, pre-push: npm run test }, lint-staged: { *.{js,vue}: [ eslint --fix, prettier --write ] } }9.2 测试策略完整的测试体系保证代码质量。// Jest单元测试 describe(Math operations, () { test(adds 1 2 to equal 3, () { expect(1 2).toBe(3); }); test(async operation, async () { const result await fetchData(); expect(result).toBe(expected data); }); }); // Vue组件测试 import { shallowMount } from vue/test-utils; import MyComponent from /components/MyComponent.vue; describe(MyComponent, () { it(renders correctly, () { const wrapper shallowMount(MyComponent, { propsData: { message: test } }); expect(wrapper.text()).toMatch(test); }); }); // E2E测试 (Cypress) describe(User journey, () { it(completes user registration, () { cy.visit(/register); cy.get([data-testidemail]).type(testexample.com); cy.get([data-testidpassword]).type(password123); cy.get([data-testidsubmit]).click(); cy.url().should(include, /dashboard); }); });10. 面试技巧与准备策略10.1 技术面试准备技术面试需要系统性的准备和练习。算法准备重点数组、字符串操作链表相关题目树结构的遍历和操作动态规划基础排序和搜索算法// 常见的算法题解法 function twoSum(nums, target) { const map new Map(); for (let i 0; i nums.length; i) { const complement target - nums[i]; if (map.has(complement)) { return [map.get(complement), i]; } map.set(nums[i], i); } return []; } // 二叉树遍历 class TreeNode { constructor(val) { this.val val; this.left this.right null; } } function inorderTraversal(root) { const result []; function traverse(node) { if (!node) return; traverse(node.left); result.push(node.val); traverse(node.right); } traverse(root); return result; }10.2 项目经验梳理如何有效展示项目经验是面试成功的关键。STAR法则描述项目Situation项目背景和业务需求Task你的具体职责和任务Action采取的技术方案和实现过程Result达成的成果和量化指标技术深度展示架构设计思路和权衡性能优化具体措施遇到的挑战和解决方案代码质量和工程化实践通过系统学习这100个前端面试核心问题结合实际项目练习你就能在字节等大厂前端面试中游刃有余。记住技术深度和解决问题的能力比死记硬背更重要理解原理并能灵活应用才是面试官最看重的素质。