js的一些經典面試題
阿新 • • 發佈:2019-02-14
年底好多小夥伴找新工作,為了面試可謂是殫精竭慮啊,但還是免不了被面試官說的一臉懵逼。哈哈哈... 今天總結點經典面試題目,有些是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
}, [])
}