在前端面试中,手写题是考察应聘者基础编程能力和对前端技术掌握程度的重要环节。以下是一些常见的前端手写题及其解答思路:
书在python33点(0M
1. 数组求和
题目:求数组 [2, 3, 4, 5, 6, 6, 7, 7, 8, 8, 8]
的总和。
解答:
javascript复制代码
const arr = [2, 3, 4, 5, 6, 6, 7, 7, 8, 8, 8]; | |
const sum = arr.reduce((total, val) => total + val, 0); | |
console.log(sum); // 输出 56 |
这里使用了数组的 reduce
方法,它接收一个回调函数和一个初始值(这里是0),通过回调函数将数组中的每个元素累加,最终得到总和。
2. 实现防抖(Debounce)函数
题目:实现一个防抖函数,该函数在指定的时间间隔内只执行一次。
解答:
javascript复制代码
function debounce(func, wait) { | |
let timeout; | |
return function() { | |
const context = this; | |
const args = arguments; | |
clearTimeout(timeout); | |
timeout = setTimeout(() => { | |
func.apply(context, args); | |
}, wait); | |
}; | |
} | |
// 使用示例 | |
const debouncedLog = debounce(console.log, 2000); | |
window.addEventListener('resize', debouncedLog); |
在这个例子中,debounce
函数接收一个要执行的函数 func
和一个等待时间 wait
。它返回一个函数,这个函数在每次被调用时都会重置一个定时器,只有在最后一次调用后等待时间 wait
过了,才会执行 func
函数。
3. 实现节流(Throttle)函数
题目:实现一个节流函数,该函数在指定的时间间隔内最多执行一次。
解答:
javascript复制代码
function throttle(func, limit) { | |
let lastFunc; | |
let lastRan; | |
return function() { | |
const context = this; | |
const args = arguments; | |
if (!lastRan) { | |
func.apply(context, args); | |
lastRan = Date.now(); | |
} else { | |
clearTimeout(lastFunc); | |
lastFunc = setTimeout(function() { | |
if ((Date.now() - lastRan) >= limit) { | |
func.apply(context, args); | |
lastRan = Date.now(); | |
} | |
}, limit - (Date.now() - lastRan)); | |
} | |
}; | |
} | |
// 使用示例 | |
const throttledLog = throttle(console.log, 1000); | |
window.addEventListener('scroll', throttledLog); |
这个 throttle
函数与 debounce
类似,但它确保了在指定的时间间隔内至少执行一次函数。它使用了一个定时器来延迟函数的执行,直到时间间隔过去或者达到下一个触发点。
4. 数组扁平化
题目:将多维数组 [1, [2, 3], [4, [5, 6]]]
扁平化为一维数组。
解答:
javascript复制代码
function flatten(arr) { | |
return arr.flat(Infinity); | |
} | |
const nestedArray = [1, [2, 3], [4, [5, 6]]]; | |
const flatArray = flatten(nestedArray); | |
console.log(flatArray); // 输出 [1, 2, 3, 4, 5, 6] |
在 ES6 中,flat
方法可以直接用来扁平化数组,Infinity
作为深度参数表示无论数组嵌套多深,都要扁平化到一维。
5. 实现继承
题目:使用 JavaScript 实现继承。
解答:
javascript复制代码
// ES5 继承 | |
function Parent(name) { | |
this.name = name; | |
} | |
Parent.prototype.getName = function() { | |
console.log(this.name); | |
}; | |
function Child(name, age) { | |
Parent.call(this, name); // 借用构造函数 | |
this.age = age; | |
} | |
Child.prototype = Object.create(Parent.prototype); // 继承父类原型 | |
Child.prototype.constructor = Child; // 修正构造函数指向 | |
// ES6 继承 | |
class Parent { | |
constructor(name) { | |
this.name = name; | |
} | |
getName() { | |
console.log(this.name); | |
} | |
} | |
class Child extends Parent { | |
constructor(name, age) { | |
super(name); // 调用父类构造函数 | |
this.age = age; | |
} | |
} | |
// 测试 | |
const child = new Child('Tom', 10); | |
child.getName(); // 输出 Tom |
这里展示了两种实现继承的方式:ES5 的寄生组合式继承和 ES6 的 class
继承。
总结
以上是一些前端面试中常见的手写题及其解答思路。这些题目涵盖了数组操作、函数式编程、继承等前端基础知识,掌握它们对于通过前端面试至关重要。