大厂高频手写题

最近面试, 投了字节, 结果人家找我约面了, 面试过程中感觉还是比较良好的, 但是最后没过, 反思了一下自己...手写体写的时间太久了, 写的久算了, 最后一道题也没写出来完, 所以整理一些题目给大家做个参考(有一面的也有二面的), 如果大家有入大厂的打算, 一定要在平时注重算法和手写题的积累...

答案放最下面了, 不是没写哦

this指向

下面输出什么?

真题1
js 复制代码
const obj = {
  value: 42,

  getValue: function () {
    console.log(this.value);
    return this.value;
  },

  getAsync: function () {
    setTimeout(() => {
      console.log(this.value);
    }, 100);
  }
};

obj.getValue();
obj.getAsync();
真题2
js 复制代码
let name = "x"
const people = {
  name: "y",
  setName(name) {
    this.name = name
    return () => {
      return this.name
    }
  }
}
let setName = people.setName
let getName = setName(name)  //里面箭头函数被重新创建了
console.log(people.name)
console.log(getName())
练习
js 复制代码
var name = 'global';

const obj = {
  name: 'obj',
  getName() {
    console.log(this.name);
  },
  getArrow() {
    return () => {
      console.log(this.name);
    };
  },
  nested: {
    name: 'nested',
    getName() {
      console.log(this.name);
    }
  }
};

const fn1 = obj.getName;
const fn2 = obj.getArrow();
const fn3 = obj.nested.getName;

obj.getName();  
fn1(); 
fn2(); 
obj.getArrow()(); 
obj.nested.getName(); 
fn3(); 

const another = {
  name: 'another'
};

obj.getName.call(another); 
obj.getArrow.call(another)(); 
答案

真题1:

42

42

真题2:

y

x

练习:

obj

global

obj

obj

nested

global

another

another

变量提升

真题1
js 复制代码
function test() {
  console.log(a);
  var a = "变量";

  function a() {
    return "函数";
  }

  console.log(a);
}
test();
真题2
js 复制代码
function outer() {
  const x = 10;

  function inner() {
    console.log(x);
    let x = 20;
  }

  inner();
}

outer();
答案

真题1:

Function: a

变量

真题2:

ReferenceError: Cannot access 'x' before initialization

时间循环

真题1
js 复制代码
console.log('1');
setTimeout(() => {
  console.log('2');
  Promise.resolve().then(() => console.log('3'));
}, 0);
new Promise((resolve) => {
  console.log('4');
  resolve();
})
  .then(() => {
    console.log('5');
    setTimeout(() => console.log('6'), 0);
  })
  .then(() => {
    console.log('7');
  });
console.log('8');
真题2
js 复制代码
async function async1() {
  console.log("async1 start");
  await async2();
  console.log("async1 end");
}

async function async2() {
  console.log("async2");
}

console.log("script start");

setTimeout(function () {
  console.log("setTimeout");
}, 0);

async1();

new Promise(function (resolve) {
  console.log("promise1");
  resolve();
}).then(function () {
  console.log("promise2");
});

console.log("script end");
练习
js 复制代码
console.log('A');


setTimeout(() => {
  console.log('B');

  Promise.resolve().then(() => {
    console.log('C');
  });

  setTimeout(() => {
    console.log('D');
  }, 0);
}, 0);

Promise.resolve().then(() => {
  console.log('E');

  setTimeout(() => {
    console.log('F');
  }, 0);

  return Promise.resolve().then(() => {
    console.log('G');
  });
}).then(() => {
  console.log('H');
});

new Promise((resolve) => {
  console.log('I');
  resolve();
}).then(() => {
  console.log('J');
});

console.log('K');
答案

真题1:

1

4

8

5

7

2

3

6

真题2:

script start

async1 start

async2

promise1

script end

async1 end

promise2

setTimeout

练习:

A

I

K

E

J

G

H

B

C

F

D

节流防抖

真题1(大家不懂可以去看一下loadsh源码)

题目:

实现 debounce:

  1. 支持基本防抖功能
  2. 支持 leading 选项
  3. 支持 cancel 方法取消防抖
js 复制代码
const test = (message) => {
  console.log(message);
};

const debouncedTest = debounce(test, 100);
debouncedTest(1);
setTimeout(() => debouncedTest(3), 150);
// 输出:1(约 100ms 后)
// 输出:3(约 250ms 后)

const debouncedTest2 = debounce(test, 300, { leading: true });
debouncedTest2("1"); // 立即输出 1
debouncedTest2("2"); // 不输出
setTimeout(() => debouncedTest2("3"), 350); // 立即输出 3
答案
js 复制代码
const debounce = function(func, wait, options= {}){
	let leading = options.leading??false;//有leading以leading为主
	let timer = null;
	let lastTime = 0;
	
	const debounced = function(...args){
		const now = Date.now();
		if(leading){
			if(now-lastTime>=wait){
				func.apply(this,args);
				lastTime = now;
			}
			return;
		}
		
		if(timer){
			clearTimeout(timer);
		}
		
		timer = setTimeout(()=>{
			func.apply(this, args); 
			timer = null;
		},wait)
		
		return timer;
	}
	debounced.cancel = function (){
		 clearTimeout(timer);
		 timer = null;
		 lastTime = 0;
	}
	return debounced;
}

EventBus

真题1
js 复制代码
class Eventimitter{ 
//注册事件
on(eventliame, callback){} 
// 触发事件
emit(eventhame,payload){} 
// 解绑事件
off(eventliame, callback){} 
//注册单次事件
once(eventliame,callback){}
}
答案
js 复制代码
class EventBus(){
	constructor(){
		this.events= {}
	}
	// 注册事件
	on(eventName, callback){
		if(!this.events[eventName]){
			this.events[eventName] = [];
		}
		this.events[eventName].push(callback);
	}
	
	// 触发事件
	emit(eventName, payload){
		if(!this.events[eventName]) return;
		this.events[eventName].forEach((callback)=>{
			callback(payload);
		})
	}
	
	// 解绑事件
	off(eventName, callback){
		if(!this.events[eventName]) return;
		this.events[eventName] = this.events[eventName].filter((fn)=>fn!==callback);
	}
	
	// 注册单次事件
	once(eventName, callback){
		const wrapper = (payload)=>{
			callback(payload);
			this.off(eventName, wrapper);
		}
		this.on(eventName,wrapper);
	}
}

react hook+useEffect+闭包

真题1
js 复制代码
import React, { useState, useEffect } from "react";

const App = () => {
  const [count, setCount] = useState(0);

  useEffect(() => {
    const timer = setInterval(() => {
      console.log("setInterval:", count);
    }, 1000);

    return () => clearInterval(timer);
  }, []);

  return (
    <div>
      count: {count}
      <br />
      <button onClick={() => setCount(count + 1)}>+1</button>
    </div>
  );
};

export default App;
答案

不管如何点击button, console都稳定输出1秒1次 setInterval, 0 (除非组件被销毁)

有一些上面没有

重点准备这些高频:

数组扁平化

防抖节流

深拷贝

Promise.all

LRU

发布订阅

柯里化

事件总线

手写call/apply/bind

字符串/数组常见题...

加油!

相关推荐
guslegend2 小时前
AI生图第2节:python对接gpt-image-2模型API生图
开发语言·python·gpt
原来是猿2 小时前
Linux线程同步与互斥(四):日志系统与策略模式
linux·运维·开发语言·策略模式
zhensherlock3 小时前
Protocol Launcher 系列:Working Copy 文件操作与高级命令详解
javascript·git·typescript·node.js·自动化·github·js
卷心菜狗3 小时前
Python进阶--迭代器
开发语言·python
jr-create(•̀⌄•́)4 小时前
LeakyRelu链式法则
开发语言·python·深度学习
神の愛9 小时前
左连接查询数据 left join
java·服务器·前端
t***54410 小时前
如何配置Orwell Dev-C++使用Clang
开发语言·c++
CoderCodingNo10 小时前
【信奥业余科普】C++ 的奇妙之旅 | 13:为什么 0.1+0.2≠0.3?——解密“爆int”溢出与浮点数精度的底层原理
开发语言·c++
小码哥_常11 小时前
解锁Android嵌入式照片选择器,让你的App体验丝滑起飞
前端