前言
9月就快来了,每年属于程序员的金9银10转会即将开始,为此,从没有写过面试相关的我,也尝试整理几篇面试题,供大伙品尝,希望用的上。主要是理解
第一题:交换两个变量的值
面试官:不借助第三方变量 和 ES6 的解构,你如何交换两个变量的值,答的越多越好 题代码如下:
let a = 1
let b = 2
// 面试者具体操作
// ...
console.log(a)//2
console.log(b)//1
题解1:
let a = 1
let b = 2
// 面试者具体操作
a = [b, (b = a)][0]
console.log(a)//2
console.log(b)//1
题解2:
let a = 1
let b = 2
// 面试者具体操作
a = a + b
b = a - b
a = a - b
//=>
// a = a + b = 1 + 2 = 3
// b = a - b = 3 - 2 = 1
// a = a - b = 3 - 1 = 2
console.log(a)//2
console.log(b)//1
题解3:
let a = 1
let b = 2
// 面试者具体操作
b ^= a
a ^= b
b ^= a
console.log(a)//2
console.log(b)//1
第二题:函数柯里化
面试官:请你实现一个
add
函数,满足以下
add(1,2,3)() // 6
add(1,2)(3)() // 6
add(1)(2)(3)() // 6
面试者陷入沉思中,“add函数 必须得返回一个函数才行,前期得有变量来储存之前的参数累加和,当该函数接收的参数为0时,即是真正的计算结果的时候...”
function add( cahce, ...args ) {
// 返回一个 func 函数
return function func( ...funcArgs ) {
if (funcArgs.length) {
// 如果 func 函数参数为不为0,就执行累计
cahce = funcArgs.reduce((p, c) => (p += c), cahce)
// 接着返回该 func 函数
return func
} else {
// 如果 func 函数参数为为0,就返回最终结果
return args.reduce((p, c) => (p += c), cahce)
}
}
}
console.log(add(1, 2, 3)()) // 6
console.log(add(1, 2)(3)()) // 6
console.log(add(1)(2)(3)()) // 6
面试官见你很麻利的答出了此题,顿时觉得你骨骼精奇,可大为之,接着道,同样是实现一个
add
方法,满足以下: 6 6 6
add(1,2,3) // 6
add(1,2)(3) // 6
add(1)(2)(3) // 6
面试者陷入沉思中,“看满足的条件,共同点就是都是 3个参数,一个函数搞定不了,需要借助一个辅助函数来完成才行...”
const curry = function (fn, ...args) {
// 函数的参数个数可以通过函数的length进行访问 fn.length
return args.length >= fn.length ? // 如果参数个数 大于等于 fn:add1 的参数个数(3)时候,就进行清算
fn(...args) :
(..._args) => curry(fn, ..._args, ...args)// 否则继续进行参数个数累加
}
const add1 = (x, y, z) => x + y + z
const add = curry(add1)
console.log(add(1, 2, 3))//6
console.log(add(1, 2)(3))//6
console.log(add(1)(2)(3))//6
第三题:数组值交换
和蔼可亲的面试官道:请你实现一个
change
函数,来交换指定数组对应索引的值,如下:
// 给出一个数组
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
const oldIndex = 7
const newIndex = 1
console.log( change(oldIndex,newIndex,arr) )// [1, 8, 3, 4, 5, 6, 7, 2, 9]
面试者陷入沉思中,“肯定要用到数组的splice
方法,当初学习的时候,老熟了(这题我会),于是...”
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
const oldIndex = 7
const newIndex = 1
function change(oldIndex, newIndex, arr) {
arr = arr.slice()
arr.splice(oldIndex, 1, arr.splice(newIndex, 1, arr[oldIndex])[0])
return arr
}
console.log(change(oldIndex, newIndex, arr)) // [1, 8, 3, 4, 5, 6, 7, 2, 9]
console.log(arr) // [1, 2, 3, 4, 5, 6, 7, 8, 9]
第四题:instanceof
发际线很高的面试官道:请你给出下面的返回值
console.log( '' instanceof String )
console.log( '123' instanceof String )
console.log( 123 instanceof Number )
面试者陷入沉思中,“这其中是否有诈,于是...”
第五题:a == 1 && a== 2 && a==3
可以为true
否?
let a = {
val:1,
valueOf(){
return this.val++
}
}
console.log(a == 1 && a== 2 && a==3) // true
后言
第一次写面试相关,关于面试题,主要是偏向于理解,理解后成功吸收成自己的才是最终目的,最后
结语
如果你有更好的点子或是疑问,欢迎留言
文中若有不准确或错误的地方,欢迎指出