年底好多小伙伴找新工作,为了面试可谓是殚精竭虑啊,但还是免不了被面试官说的一脸懵逼。哈哈哈... 今天总结点经典面试题目,有些是es6,有些是es5。
不要吐槽我 -.-
1.记忆化斐波那契函数(Memoization)
Q1:数组 [1, 1, 2, 3, 5, 8, 13, ....]
请你完成 fibonacci 函数,接受 n 作为参数,可以获取数列中第 n 个数.
A1:
const fibonacci = ((memo = [0, 1]) => {
const fib = (n) => {
let result = memo[n]
if (typeof result !== "number") {
result = fib(n - 1) + fib(n - 2)
memo[n] = result
}
return result
}
return fib
})()
2.解析字串
Q2:完成一个 extractStr 函数,可以把一个字符串中所有的 : 到 . 的子串解析出来并且存放到一个数组当中
A2:
const extractStr = (str) => {
const ret = str.match(/:([^:\.])*?\./g) || []
return ret.map((subStr) => subStr.replace(/[:\.]/g, ''))
}
3.safeGet
Q3:请你完成一个 safeGet 函数,可以安全的获取无限多层次的数据,一旦数据不存在不会报错,会返回 undefined
A3:
const safeGet = (o, path) => {
try {
return path.split('.').reduce((o, k) => o[k], o)
} catch (e) {
return void 666
}
}
4.判断两个矩形是否重叠
Q4:请你完成一个函数 isOverlap 可以接受两个矩形作为参数,判断这两个矩形在页面上是否重叠
A4:
// 原理:http://www.geeksforgeeks.org/find-two-rectangles-overlap/
const isOverlap = (rect1, rect2) => {
const l1 = { x: rect1.x, y: rect1.y }
const r1 = { x: rect1.x + rect1.width, y: rect1.y + rect1.height }
const l2 = { x: rect2.x, y: rect2.y }
const r2 = { x: rect2.x + rect2.width, y: rect2.y + rect2.height }
if (
l1.x > r2.x ||
l2.x > r1.x ||
l1.y > r2.y ||
l2.y > r1.y
) return false
return true
}
5.spacify
Q5:请你给字符串都添加上原型方法 spacify,可以让一个字符串的每个字母都多出一个空格的间隔
A5:
String.prototype.spacify = function () {
return this.split('').join(' ')
}
6.按下标插入
Q6:有两个数组,arr1=['item1', 'item2', 'item3', 'item4', 'item5'],arr2 = [{content: 'section1', index: 0 },{content:
'section2', index: 2}]
请你完成 injectSections 函数,最后结果是:['section1', 'item1', 'item2', 'section2', 'item3', 'item4', 'item5']
A6:
//研究了好一段时间 - -
const injectSections = (items, sections) => {
/* 需要插入坐标对应数据存放到 map 里面 */
const sectionsMap = new Map(sections.map(({ index, content }) => [index, content]))
/* 新建一个数组,然后往里面 push 原来数组的数据 */
return items.reduce((ret, item, index) => {
/* push 的时候先检查 map 里面有没有,有的话先 push map 里面的数据 */
if (sectionsMap.has(index)) ret.push(sectionsMap.get(index))
/* 再 push 原来的数据 */
ret.push(item)
return ret
}, [])
}