前端面试题
1. 前端如何处理后端接口返回的超大树形结构数据?(考察应聘者海量数据处理能力)
- 虚拟滚动:对于大型树形结构,虚拟滚动是最佳选择,它只渲染当前可见的部分。
- 懒加载:只加载当前展开节点的子节点,减少初始数据量。
- 数据分片处理:树结构实在太大,可以考虑分片加载。(其实就是服务端分页)
- Web Worker处理:worker文件(如ts文件)
子进程
self.onmessage = function (e) {
const { data, action} = e.data
let result
switch (action) {
case 'filter':
result = filterTree (data, e.data.query) // 查询的数据
break
case 'flatten':
result = flattenTree (data) // 组合的数据
break
}
selt.postMessage(result) // 数据发给主线程
}
主进程
const processLargeData = async (data: any[], action: string) => { return new Promise((resolve) => { const worker = new Worker(new URL('./worker.ts', import.meta.url)) // 起一个进程指向worker.ts worker.postMessage({data, action}) // post给子线程 worker.onmessage = (e) => { // 接受数据 resove(e.data) worker.terminate() // worker销毁 } }) }
2. 同一链接,如何实现PC打开进入Web页,手机打开进入H5应用?(考察应聘者对浏览器的类型能力)
- 前端 JavaScript 检测设备:通过 JavaScript 检测设备类型,然后跳转到对应的应用
// 检测设备类型 function detectDevice () { const userAgent = navigator.userAgent.toLowerCase() const isMobile = /iphone|ipod|ipad|android|mobile|phone/i.test(userAgent) return isMobile ? 'mobile' : 'pc' }
- 屏幕尺寸检测:有些设备(如平板)可能同时匹配PC和移动端,可以结合屏幕宽度优化判断
function detectDevice () { const userAgent = navigator.userAgent.toLowerCase() const isMobileUA = /iphone|ipod|ipad|android|mobile|phone|touch|mini|silk/i.test(userAgent) const isSmallScreen = window.innerWidth < 768; // 768px是常见的移动端分界点 // 如果 User-Agent 判断是移动端,或者屏幕较小,则认为是移动设备 return (isMobileUA || isSmallScreen) ? 'mobile' : 'pc" }
- 延迟重定向(避免影响SEO):重定向影响搜索引擎抓取,可以延迟跳转
setTimeout(() => { const userAgent = navigator.userAgent const isMobile = /iphonMe|android|mobile/i.test(userAgent) window.location.href = isMobile ? '/h5-app' : '/web-app' }, 100) // 延迟100ms,让SEO工具先抓取原始页面
3. AI 工具中,经常提到的 mcp 是什么,有哪些与前端方向结合的场景?
- MCP:模型上下文协议(Model Context Protocol)
- 开放标准 AI模型 安全、结构化与外部工具、数据源、和服务进行通信
- AI模型 => 大脑
- mcp => usb标准
- mcp工具 => 外设
mcp组成部分
- mcp客户端:工具调用
- mcp服务器:提供具体功能的程序
- 协议:通信规则
让AI模型变成了智能体
MCP和前端方向结合的场景
- 使用MCP增强前端开发流程
- AI辅助开发提效
- cursor
- 项目上下文感知 mcp连接文件系统
- API集成助手
- 设计稿转代码:mcp连接figma插件工具
- 开发具有MCP能力的下一代前端应用
4. axios 是如何区分是 nodejs 环境还是浏览器环境
全局变量 和 运行环境
- 判断全局变量
- nodejs 环境下,global
- 浏览器环境下,window self
- 判断 process 变量
- typeof process === 'object' && process.versions && process.versions.node (nodejs 环境才有 process)
- isStandardBrowserEnv 函数
- 是否为标准浏览器环境,会排除 web worker、react-native、nodejs 等环境
function isStandarBrowserEnv () { if (typeof navigator !== 'undefined' && ['ReactNative', 'NativeScript', 'NS'].includes(navigator.product)) { return false } return typeof window !== 'undefined' && typeof document !== 'undefined' }
- 条件导出不同的适配器
- 根据环境选择不同的请求适配器 adapter
- 浏览器 XMLHttpRequest
- nodejs http/https 模块
- 根据环境选择不同的请求适配器 adapter
1 if (typeof XMLHttpRequest !== 'undefined') { 2 // 浏览器环境 3 adapter = require('./adapter/xhr') 4 } else if (typeof process !== 'undefined' && Object.prototype.toString.call(process) === '[object process]') { 5 // nodejs环境 6 }

浙公网安备 33010602011771号