柚子快报激活码778899分享:面试20题:-12-25面试题 - return 1
柚子快报激活码778899分享:面试20题:-12-25面试题
JavaScript 面试题详解
本文档包含10个常见的JavaScript面试题,每个题目都配有详细的解答和代码实例。
1. 数组去重的方式都有哪些?
方法一:使用 Set(ES6,推荐)
const arr = [1, 2, 2, 3, 4, 4, 5];
const uniqueArr = [...new Set(arr)];
console.log(uniqueArr); // [1, 2, 3, 4, 5]
方法二:使用 filter + indexOf
const arr = [1, 2, 2, 3, 4, 4, 5];
const uniqueArr = arr.filter((item, index) => arr.indexOf(item) === index);
console.log(uniqueArr); // [1, 2, 3, 4, 5]
方法三:使用 reduce
const arr = [1, 2, 2, 3, 4, 4, 5];
const uniqueArr = arr.reduce((acc, current) => {
if (!acc.includes(current)) {
acc.push(current);
}
return acc;
}, []);
console.log(uniqueArr); // [1, 2, 3, 4, 5]
方法四:使用 for 循环 + includes
const arr = [1, 2, 2, 3, 4, 4, 5];
const uniqueArr = [];
for (let i = 0; i < arr.length; i++) {
if (!uniqueArr.includes(arr[i])) {
uniqueArr.push(arr[i]);
}
}
console.log(uniqueArr); // [1, 2, 3, 4, 5]
方法五:使用 Map(适合对象数组)
const arr = [{id: 1, name: 'a'}, {id: 2, name: 'b'}, {id: 1, name: 'a'}];
const map = new Map();
arr.forEach(item => {
map.set(item.id, item);
});
const uniqueArr = Array.from(map.values());
console.log(uniqueArr); // [{id: 1, name: 'a'}, {id: 2, name: 'b'}]
性能对比
Set方法:性能最好,代码最简洁,推荐使用filter + indexOf:代码简洁,但性能较差(O(n²))reduce:可读性好,性能中等for循环:性能较好,但代码较冗长
2. 手写深拷贝的逻辑,讲述一下?
深拷贝的概念
深拷贝是指创建一个新对象,完全复制原对象的所有属性,包括嵌套的对象和数组,修改新对象不会影响原对象。
方法一:使用 JSON.parse(JSON.stringify())(简单场景)
const obj = {
name: 'John',
age: 30,
hobbies: ['reading', 'coding'],
address: {
city: 'Beijing',
country: 'China'
}
};
const deepCopy = JSON.parse(JSON.stringify(obj));
deepCopy.address.city = 'Shanghai';
console.log(obj.address.city); // 'Beijing' - 原对象未改变
console.log(deepCopy.address.city); // 'Shanghai'
局限性:
不能处理函数、undefined、Symbol不能处理循环引用会丢失 Date 对象(转为字符串)
方法二:递归实现(完整版)
function deepClone(target, map = new WeakMap()) {
// 处理 null 和基本类型
if (target === null || typeof target !== 'object') {
return target;
}
// 处理 Date
if (target instanceof Date) {
return new Date(target);
}
// 处理 RegExp
if (target instanceof RegExp) {
return new RegExp(target);
}
// 处理循环引用
if (map.has(target)) {
return map.get(target);
}
// 处理数组
if (Array.isArray(target)) {
const cloneArr = [];
map.set(target, cloneArr);
target.forEach((item, index) => {
cloneArr[index] = deepClone(item, map);
});
return cloneArr;
}
// 处理对象
const cloneObj = {};
map.set(target, cloneObj);
for (let key in target) {
if (target.hasOwnProperty(key)) {
cloneObj[key] = deepClone(target[key], map);
}
}
return cloneObj;
}
// 测试
const original = {
name: 'John',
date: new Date(),
arr: [1, 2, { nested: 'value' }],
func: function() { return 'test'; }
};
original.self = original; // 循环引用
const cloned = deepClone(original);
cloned.name = 'Jane';
cloned.arr[2].nested = 'changed';
console.log(original.name); // 'John'
console.log(original.arr[2].nested); // 'value'
方法三:使用 structuredClone(现代浏览器)
// 浏览器环境支持(Node.js 17+)
const obj = { name: 'John', nested: { value: 123 } };
const cloned = structuredClone(obj);
cloned.nested.value = 456;
console.log(obj.nested.value); // 123
3. this 指向的理解?
this 的绑定规则
规则一:默认绑定(全局调用)
function foo() {
console.log(this); // 浏览器中指向 window,严格模式下为 undefined
}
foo();
规则二:隐式绑定(对象方法调用)
const obj = {
name: 'John',
sayHello: function() {
console.log(this.name); // 'John' - this 指向 obj
}
};
obj.sayHello();
规则三:显式绑定(call、apply、bind)
function greet() {
console.log(`Hello, ${this.name}`);
}
const person1 = { name: 'Alice' };
const person2 = { name: 'Bob' };
greet.call(person1); // 'Hello, Alice'
greet.apply(person2); // 'Hello, Bob'
const boundGreet = greet.bind(person1);
boundGreet(); // 'Hello, Alice'
规则四:new 绑定(构造函数)
function Person(name) {
this.name = name; // this 指向新创建的对象
}
const person = new Person('John');
console.log(person.name); // 'John'
规则五:箭头函数(词法绑定)
const obj = {
name: 'John',
regular: function() {
console.log(this.name); // 'John'
},
arrow: () => {
console.log(this.name); // undefined - this 指向外层作用域(全局)
},
nested: function() {
const inner = () => {
console.log(this.name); // 'John' - 箭头函数继承外层 this
};
inner();
}
};
obj.regular();
obj.arrow();
obj.nested();
this 绑定优先级
new 绑定 > 显式绑定 > 隐式绑定 > 默认绑定箭头函数的 this 在定义时确定,无法改变
4. 如何使用 Promise 封装原生 Ajax?
封装 GET 请求
function ajaxGet(url) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 300) {
try {
const data = JSON.parse(xhr.responseText);
resolve(data);
} catch (e) {
resolve(xhr.responseText);
}
} else {
reject(new Error(`请求失败: ${xhr.status}`));
}
}
};
xhr.onerror = function() {
reject(new Error('网络错误'));
};
xhr.send();
});
}
// 使用示例
ajaxGet('https://api.example.com/data')
.then(data => console.log('成功:', data))
.catch(error => console.error('失败:', error));
封装 POST 请求(完整版)
function ajax(options) {
return new Promise((resolve, reject) => {
const {
url,
method = 'GET',
data = null,
headers = {},
timeout = 0
} = options;
const xhr = new XMLHttpRequest();
xhr.open(method, url, true);
// 设置请求头
Object.keys(headers).forEach(key => {
xhr.setRequestHeader(key, headers[key]);
});
// 设置超时
if (timeout > 0) {
xhr.timeout = timeout;
xhr.ontimeout = () => {
reject(new Error('请求超时'));
};
}
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 300) {
try {
const response = xhr.responseText;
const contentType = xhr.getResponseHeader('Content-Type');
if (contentType && contentType.includes('application/json')) {
resolve(JSON.parse(response));
} else {
resolve(response);
}
} catch (e) {
reject(new Error('解析响应失败'));
}
} else {
reject(new Error(`请求失败: ${xhr.status}`));
}
}
};
xhr.onerror = function() {
reject(new Error('网络错误'));
};
// 发送请求
if (data && method !== 'GET') {
if (typeof data === 'object') {
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify(data));
} else {
xhr.send(data);
}
} else {
xhr.send();
}
});
}
// 使用示例
ajax({
url: 'https://api.example.com/users',
method: 'POST',
data: { name: 'John', age: 30 },
headers: {
'Content-Type': 'application/json'
},
timeout: 5000
})
.then(data => console.log('成功:', data))
.catch(error => console.error('失败:', error));
使用 async/await
async function fetchData() {
try {
const data = await ajax({
url: 'https://api.example.com/data',
method: 'GET'
});
console.log('数据:', data);
} catch (error) {
console.error('错误:', error);
}
}
fetchData();
5. 箭头函数和普通函数的区别?
主要区别对比
1. this 绑定
const obj = {
name: 'John',
regular: function() {
console.log(this.name); // 'John'
},
arrow: () => {
console.log(this.name); // undefined(this 指向全局对象)
}
};
obj.regular();
obj.arrow();
2. arguments 对象
function regular() {
console.log(arguments); // 类数组对象
}
const arrow = () => {
console.log(arguments); // ReferenceError: arguments is not defined
};
regular(1, 2, 3);
arrow(1, 2, 3);
3. 作为构造函数
function Regular(name) {
this.name = name; // 可以
} 拼多多帮助力入口
const Arrow = (name) => {
this.name = name; // 不可以
};
const r = new Regular('John'); // ✅
const a = new Arrow('John'); // ❌ TypeError: Arrow is not a constructor
4. 原型属性
function Regular() {}
Regular.prototype.method = function() {};
const Arrow = () => {};
Arrow.prototype.method = function() {}; // 无意义,箭头函数没有 prototype
5. 提升(Hoisting)
regular(); // ✅ 可以调用(函数声明提升)
function regular() {
console.log('regular');
}
arrow(); // ❌ ReferenceError(变量提升,但未初始化)
const arrow = () => {
console.log('arrow');
};
6. 简洁语法
// 普通函数
const add1 = function(a, b) {
return a + b;
};
// 箭头函数
const add2 = (a, b) => a + b;
// 单参数可省略括号
const square = x => x * x;
// 无参数需要括号
const greet = () => 'Hello';
使用场景建议
使用箭头函数:
回调函数(map、filter、forEach等)需要保持外层 this 的场景简短的单行函数
使用普通函数:
需要作为构造函数需要动态 this 绑定需要 arguments 对象对象方法(通常)
6. 浏览器环境中事件循环的理解?
事件循环机制
JavaScript 是单线程语言,通过事件循环(Event Loop)实现异步操作。
执行栈和任务队列
console.log('1'); // 同步任务
setTimeout(() => {
console.log('2'); // 宏任务
}, 0);
Promise.resolve().then(() => {
console.log('3'); // 微任务
});
console.log('4'); // 同步任务
// 输出顺序:1, 4, 3, 2
执行顺序
同步任务:直接执行微任务(Microtask):Promise.then、queueMicrotask、MutationObserver宏任务(Macrotask):setTimeout、setInterval、I/O操作、UI渲染
完整示例
console.log('start'); // 1
setTimeout(() => {
console.log('timeout1'); // 5
Promise.resolve().then(() => {
console.log('promise2'); // 6
});
}, 0);
Promise.resolve().then(() => {
console.log('promise1'); // 3
setTimeout(() => {
console.log('timeout2'); // 7
}, 0);
});
console.log('end'); // 2
// 输出顺序:start, end, promise1, timeout1, promise2, timeout2
事件循环流程图
┌─────────────────┐
│ 执行栈 │
│ (同步代码) │
└────────┬────────┘
│
▼
┌─────────────────┐
│ 微任务队列 │ ◄─── Promise.then, queueMicrotask
│ (Microtask) │
└────────┬────────┘
│
▼
┌─────────────────┐
│ 宏任务队列 │ ◄─── setTimeout, setInterval
│ (Macrotask) │
└─────────────────┘
实际应用
// 场景:DOM 更新后执行
button.addEventListener('click', () => {
console.log('click'); // 宏任务
Promise.resolve().then(() => {
console.log('promise'); // 微任务,在 click 之后执行
});
setTimeout(() => {
console.log('timeout'); // 宏任务,最后执行
}, 0);
});
7. === 和 Object.is() 的区别?
=== 严格相等
console.log(1 === 1); // true
console.log(1 === '1'); // false(类型不同)
console.log(NaN === NaN); // false ⚠️
console.log(+0 === -0); // true ⚠️
console.log(null === null); // true
console.log(undefined === undefined); // true
Object.is() 同值相等
console.log(Object.is(1, 1)); // true
console.log(Object.is(1, '1')); // false
console.log(Object.is(NaN, NaN)); // true ✅
console.log(Object.is(+0, -0)); // false ✅
console.log(Object.is(null, null)); // true
console.log(Object.is(undefined, undefined)); // true
主要区别
比较===Object.is()NaN === NaNfalsetrue+0 === -0truefalse其他情况相同相同实现 Object.is() 的 polyfill
if (!Object.is) {
Object.is = function(x, y) {
// 处理 NaN
if (x !== x && y !== y) {
return true;
}
// 处理 +0 和 -0
if (x === 0 && y === 0) {
return 1 / x === 1 / y;
}
// 其他情况使用 ===
return x === y;
};
}
使用场景
// === 适用于大多数场景
if (value === target) { }
// Object.is() 适用于特殊值比较
if (Object.is(value, NaN)) { } // 检查 NaN
if (Object.is(value, -0)) { } // 区分 +0 和 -0
8. Promise 的理解?
Promise 基本概念
Promise 是异步编程的解决方案,表示一个异步操作的最终完成或失败。
三种状态
// 1. pending(等待中)
const p1 = new Promise(() => {});
// 2. fulfilled(已成功)
const p2 = Promise.resolve('success');
// 3. rejected(已失败)
const p3 = Promise.reject('error');
基本用法
const promise = new Promise((resolve, reject) => {
// 异步操作
setTimeout(() => {
const success = true;
if (success) {
resolve('操作成功');
} else {
reject('操作失败');
}
}, 1000);
});
promise
.then(result => {
console.log(result); // '操作成功'
})
.catch(error => {
console.error(error); // '操作失败'
})
.finally(() => {
console.log('完成'); // 无论成功失败都会执行
});
Promise 链式调用
Promise.resolve(1)
.then(value => {
console.log(value); // 1
return value + 1;
})
.then(value => {
console.log(value); // 2
return Promise.resolve(value + 1);
})
.then(value => {
console.log(value); // 3
});
Promise 静态方法
Promise.all() - 全部成功才成功
const p1 = Promise.resolve(1);
const p2 = Promise.resolve(2);
const p3 = Promise.resolve(3);
Promise.all([p1, p2, p3])
.then(values => {
console.log(values); // [1, 2, 3]
});
// 如果有一个失败
Promise.all([p1, Promise.reject('error'), p3])
.catch(error => {
console.error(error); // 'error'
});
Promise.allSettled() - 等待所有完成
Promise.allSettled([
Promise.resolve(1),
Promise.reject('error'),
Promise.resolve(3)
])
.then(results => {
console.log(results);
// [
// { status: 'fulfilled', value: 1 },
// { status: 'rejected', reason: 'error' },
// { status: 'fulfilled', value: 3 }
// ]
});
Promise.race() - 第一个完成
const p1 = new Promise(resolve => setTimeout(() => resolve('p1'), 1000));
const p2 = new Promise(resolve => setTimeout(() => resolve('p2'), 500));
Promise.race([p1, p2])
.then(value => {
console.log(value); // 'p2'(更快完成)
});
Promise.any() - 第一个成功
Promise.any([
Promise.reject('error1'),
Promise.resolve('success'),
Promise.reject('error2')
])
.then(value => {
console.log(value); // 'success'
});
手写 Promise(简化版)
class MyPromise {
constructor(executor) {
this.state = 'pending';
this.value = undefined;
this.reason = undefined;
this.onFulfilledCallbacks = [];
this.onRejectedCallbacks = [];
const resolve = (value) => {
if (this.state === 'pending') {
this.state = 'fulfilled';
this.value = value;
this.onFulfilledCallbacks.forEach(fn => fn());
}
};
const reject = (reason) => {
if (this.state === 'pending') {
this.state = 'rejected';
this.reason = reason;
this.onRejectedCallbacks.forEach(fn => fn());
}
};
try {
executor(resolve, reject);
} catch (error) {
reject(error);
}
}
then(onFulfilled, onRejected) {
return new MyPromise((resolve, reject) => {
if (this.state === 'fulfilled') {
try {
const result = onFulfilled(this.value);
resolve(result);
} catch (error) {
reject(error);
}
} else if (this.state === 'rejected') {
try {
const result = onRejected(this.reason);
resolve(result);
} catch (error) {
reject(error);
}
} else {
this.onFulfilledCallbacks.push(() => {
try {
const result = onFulfilled(this.value);
resolve(result);
} catch (error) {
reject(error);
}
});
this.onRejectedCallbacks.push(() => {
try {
const result = onRejected(this.reason);
resolve(result);
} catch (error) {
reject(error);
}
});
}
});
}
catch(onRejected) {
return this.then(null, onRejected);
}
}
9. 递归函数的理解?
递归基本概念
递归是函数调用自身的一种编程技巧,通常用于解决可以分解为相同子问题的问题。
递归三要素
终止条件(Base Case)递归调用(Recursive Call)问题规模缩小(Progress)
经典示例
1. 阶乘
function factorial(n) {
// 终止条件
if (n <= 1) {
return 1;
}
// 递归调用 + 问题规模缩小
return n * factorial(n - 1);
}
console.log(factorial(5)); // 120
2. 斐波那契数列
function fibonacci(n) {
if (n <= 1) {
return n;
}
return fibonacci(n - 1) + fibonacci(n - 2);
}
console.log(fibonacci(6)); // 8
3. 数组求和
function sum(arr) {
if (arr.length === 0) {
return 0;
}
return arr[0] + sum(arr.slice(1));
}
console.log(sum([1, 2, 3, 4, 5])); // 15
4. 树形结构遍历
const tree = {
name: 'root',
children: [
{
name: 'child1',
children: [
{ name: 'grandchild1', children: [] },
{ name: 'grandchild2', children: [] }
]
},
{
name: 'child2',
children: []
}
]
};
function traverse(node) {
console.log(node.name);
node.children.forEach(child => {
traverse(child); // 递归遍历子节点
});
}
traverse(tree);
// 输出:root, child1, grandchild1, grandchild2, child2
5. 深拷贝(递归实现)
function deepClone(obj) {
if (obj === null || typeof obj !== 'object') {
return obj;
}
if (Array.isArray(obj)) {
return obj.map(item => deepClone(item));
}
const cloned = {};
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
cloned[key] = deepClone(obj[key]);
}
}
return cloned;
}
尾递归优化
// 普通递归(可能栈溢出)
function factorial(n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
}
// 尾递归(优化后)
function factorialTail(n, acc = 1) {
if (n <= 1) return acc;
return factorialTail(n - 1, n * acc);
}
console.log(factorialTail(5)); // 120
递归 vs 迭代
// 递归版本
function factorialRecursive(n) {
if (n <= 1) return 1;
return n * factorialRecursive(n - 1);
}
// 迭代版本
function factorialIterative(n) {
let result = 1;
for (let i = 2; i <= n; i++) {
result *= i;
}
return result;
}
注意事项
栈溢出:递归深度过大会导致栈溢出性能:某些情况下迭代可能更高效可读性:递归代码通常更简洁易读
10. 快速排序的逻辑是什么?
快速排序原理
快速排序采用分治法(Divide and Conquer):
选择一个基准元素(pivot)将数组分为两部分:小于基准和大于基准递归排序两部分合并结果
基本实现
function quickSort(arr) {
// 终止条件
if (arr.length <= 1) {
return arr;
}
// 选择基准(这里选择中间元素)
const pivotIndex = Math.floor(arr.length / 2);
const pivot = arr[pivotIndex];
// 分割数组
const left = [];
const right = [];
const equal = [];
for (let i = 0; i < arr.length; i++) {
if (arr[i] < pivot) {
left.push(arr[i]);
} else if (arr[i] > pivot) {
right.push(arr[i]);
} else {
equal.push(arr[i]);
}
}
// 递归排序并合并
return [...quickSort(left), ...equal, ...quickSort(right)];
}
const arr = [64, 34, 25, 12, 22, 11, 90];
console.log(quickSort(arr)); // [11, 12, 22, 25, 34, 64, 90]
原地排序版本(更高效)
function quickSortInPlace(arr, left = 0, right = arr.length - 1) {
if (left < right) {
// 分区操作,返回基准索引
const pivotIndex = partition(arr, left, right);
// 递归排序左右两部分
quickSortInPlace(arr, left, pivotIndex - 1);
quickSortInPlace(arr, pivotIndex + 1, right);
}
return arr;
}
function partition(arr, left, right) {
// 选择最右边元素作为基准
const pivot = arr[right];
let i = left - 1; // 小于基准的元素的索引
for (let j = left; j < right; j++) {
// 如果当前元素小于基准
if (arr[j] < pivot) {
i++;
[arr[i], arr[j]] = [arr[j], arr[i]]; // 交换
}
}
// 将基准放到正确位置
[arr[i + 1], arr[right]] = [arr[right], arr[i + 1]];
return i + 1;
}
const arr = [64, 34, 25, 12, 22, 11, 90];
quickSortInPlace(arr);
console.log(arr); // [11, 12, 22, 25, 34, 64, 90]
执行过程示例
初始数组: [64, 34, 25, 12, 22, 11, 90]
第一轮(pivot = 12):
left: [11]
equal: [12]
right: [64, 34, 25, 22, 90]
递归排序 right:
第二轮(pivot = 25):
left: [22]
equal: [25]
right: [64, 34, 90]
递归排序 right:
第三轮(pivot = 34):
left: []
equal: [34]
right: [64, 90]
递归排序 right:
第四轮: [64, 90] ->[64, 90]
最终结果: [11, 12, 22, 25, 34, 64, 90]
时间复杂度
平均情况:O(n log n)最好情况:O(n log n)最坏情况:O(n²)(当数组已排序且选择最差基准时)
优化策略
// 1. 三数取中法选择基准
function getMedian(arr, left, right) {
const mid = Math.floor((left + right) / 2);
if (arr[left] > arr[mid]) [arr[left], arr[mid]] = [arr[mid], arr[left]];
if (arr[left] > arr[right]) [arr[left], arr[right]] = [arr[right], arr[left]];
if (arr[mid] > arr[right]) [arr[mid], arr[right]] = [arr[right], arr[mid]];
return mid;
}
// 2. 小数组使用插入排序
function quickSortOptimized(arr, left = 0, right = arr.length - 1) {
if (right - left < 10) {
// 小数组使用插入排序
insertionSort(arr, left, right);
return;
}
const pivotIndex = partition(arr, left, right);
quickSortOptimized(arr, left, pivotIndex - 1);
quickSortOptimized(arr, pivotIndex + 1, right);
}
总结
本文档涵盖了10个常见的JavaScript面试题,包括:
数组去重:多种方法及其性能对比深拷贝:递归实现和边界情况处理this指向:五种绑定规则和优先级Promise封装Ajax:完整的异步请求封装箭头函数:与普通函数的六大区别事件循环:微任务和宏任务的执行顺序Object.is():与 === 的区别和特殊值处理Promise:状态、方法和手写实现递归函数:三要素和经典应用场景快速排序:分治法思想和优化策略
每个题目都配有详细的代码示例和说明,适合面试准备和深入学习。
柚子快报激活码778899分享:面试20题:-12-25面试题