2024年前端最新32个手写JS,巩固你的JS基础(面试高频),2024年最新程序员面试试题

最后

喜欢的话别忘了关注、点赞哦~

开源分享:【大厂前端面试题解析+核心总结学习笔记+真实项目实战+最新讲解视频】

前端校招面试题精编解析大全

方法二:两层for循环+splice

const unique1 = arr => {

let len = arr.length;

for (let i = 0; i < len; i++) {

for (let j = i + 1; j < len; j++) {

if (arr[i] === arr[j]) {

arr.splice(j, 1);

// 每删除一个树,j–保证j的值经过自加后不变。同时,len–,减少循环次数提升性能

len–;

j–;

}

}

}

return arr;

}

方法三:利用indexOf

const unique2 = arr => {

const res = [];

for (let i = 0; i < arr.length; i++) {

if (res.indexOf(arr[i]) === -1) res.push(arr[i]);

}

return res;

}

当然也可以用include、filter,思路大同小异。

方法四:利用include

const unique3 = arr => {

const res = [];

for (let i = 0; i < arr.length; i++) {

if (!res.includes(arr[i])) res.push(arr[i]);

}

return res;

}

方法五:利用filter

const unique4 = arr => {

return arr.filter((item, index) => {

return arr.indexOf(item) === index;

});

}

方法六:利用Map

const unique5 = arr => {

const map = new Map();

const res = [];

for (let i = 0; i < arr.length; i++) {

if (!map.has(arr[i])) {

map.set(arr[i], true)

res.push(arr[i]);

}

}

return res;

}

03.类数组转化为数组


类数组是具有length属性,但不具有数组原型上的方法。常见的类数组有arguments、DOM操作方法返回的结果。

方法一:Array.from

Array.from(document.querySelectorAll(‘div’))

方法二:Array.prototype.slice.call()

Array.prototype.slice.call(document.querySelectorAll(‘div’))

方法三:扩展运算符

[…document.querySelectorAll(‘div’)]

方法四:利用concat

Array.prototype.concat.apply([], document.querySelectorAll(‘div’));

04.Array.prototype.filter()


Array.prototype.filter = function(callback, thisArg) {

if (this == undefined) {

throw new TypeError(‘this is null or not undefined’);

}

if (typeof callback !== ‘function’) {

throw new TypeError(callback + ‘is not a function’);

}

const res = [];

// 让O成为回调函数的对象传递(强制转换对象)

const O = Object(this);

// >>>0 保证len为number,且为正整数

const len = O.length >>> 0;

for (let i = 0; i < len; i++) {

// 检查i是否在O的属性(会检查原型链)

if (i in O) {

// 回调函数调用传参

if (callback.call(thisArg, O[i], i, O)) {

res.push(O[i]);

}

}

}

return res;

}

05.Array.prototype.map()


Array.prototype.map = function(callback, thisArg) {

if (this == undefined) {

throw new TypeError(‘this is null or not defined’);

}

if (typeof callback !== ‘function’) {

throw new TypeError(callback + ’ is not a function’);

}

const res = [];

// 同理

const O = Object(this);

const len = O.length >>> 0;

for (let i = 0; i < len; i++) {

if (i in O) {

// 调用回调函数并传入新数组

res[i] = callback.call(thisArg, O[i], i, this);

}

}

return res;

}

06.Array.prototype.forEach()


forEach跟map类似,唯一不同的是forEach是没有返回值的。

Array.prototype.forEach = function(callback, thisArg) {

if (this == null) {

throw new TypeError(‘this is null or not defined’);

}

if (typeof callback !== “function”) {

throw new TypeError(callback + ’ is not a function’);

}

const O = Object(this);

const len = O.length >>> 0;

let k = 0;

while (k < len) {

if (k in O) {

callback.call(thisArg, O[k], k, O);

}

k++;

}

}

07.Array.prototype.reduce()


Array.prototype.reduce = function(callback, initialValue) {

if (this == undefined) {

throw new TypeError(‘this is null or not defined’);

}

if (typeof callback !== ‘function’) {

throw new TypeError(callbackfn + ’ is not a function’);

}

const O = Object(this);

const len = this.length >>> 0;

let accumulator = initialValue;

let k = 0;

// 如果第二个参数为undefined的情况下

// 则数组的第一个有效值作为累加器的初始值

if (accumulator === undefined) {

while (k < len && !(k in O)) {

k++;

}

// 如果超出数组界限还没有找到累加器的初始值,则TypeError

if (k >= len) {

throw new TypeError(‘Reduce of empty array with no initial value’);

}

accumulator = O[k++];

}

while (k < len) {

if (k in O) {

accumulator = callback.call(undefined, accumulator, O[k], k, O);

}

k++;

}

return accumulator;

}

08.Function.prototype.apply()


第一个参数是绑定的this,默认为window,第二个参数是数组或类数组

Function.prototype.apply = function(context = window, args) {

if (typeof this !== ‘function’) {

throw new TypeError(‘Type Error’);

}

const fn = Symbol(‘fn’);

context[fn] = this;

const res = contextfn;

delete context[fn];

return res;

}

09.Function.prototype.call


call唯一不同的是,call()方法接受的是一个参数列表

Function.prototype.call = function(context = window, …args) {

if (typeof this !== ‘function’) {

throw new TypeError(‘Type Error’);

}

const fn = Symbol(‘fn’);

context[fn] = this;

const res = contextfn;

delete context[fn];

return res;

}

10.Function.prototype.bind


Function.prototype.bind = function(context, …args) {

if (typeof this !== ‘function’) {

throw new Error(“Type Error”);

}

// 保存this的值

var self = this;

return function F() {

// 考虑new的情况

if(this instanceof F) {

return new self(…args, …arguments)

}

return self.apply(context, […args, …arguments])

}

}

11.debounce(防抖)


触发高频时间后n秒内函数只会执行一次,如果n秒内高频时间再次触发,则重新计算时间。

const debounce = (fn, time) => {

let timeout = null;

return function() {

clearTimeout(timeout)

timeout = setTimeout(() => {

fn.apply(this, arguments);

}, time);

}

};

防抖常应用于用户进行搜索输入节约请求资源,window触发resize事件时进行防抖只触发一次。

12.throttle(节流)


高频时间触发,但n秒内只会执行一次,所以节流会稀释函数的执行频率。

const throttle = (fn, time) => {

let flag = true;

return function() {

if (!flag) return;

flag = false;

setTimeout(() => {

fn.apply(this, arguments);

flag = true;

}, time);

}

}

节流常应用于鼠标不断点击触发、监听滚动事件。

13.函数珂里化


指的是将一个接受多个参数的函数 变为 接受一个参数返回一个函数的固定形式,这样便于再次调用,例如f(1)(2)

经典面试题:实现add(1)(2)(3)(4)=10;add(1)(1,2,3)(2)=9;

function add() {

const _args = […arguments];

function fn() {

_args.push(…arguments);

return fn;

}

fn.toString = function() {

return _args.reduce((sum, cur) => sum + cur);

}

return fn;

}

14.模拟new操作


3个步骤:

  1. ctor.prototype为原型创建一个对象。

  2. 执行构造函数并将this绑定到新创建的对象上。

  3. 判断构造函数执行返回的结果是否是引用数据类型,若是则返回构造函数执行的结果,否则返回创建的对象。

function newOperator(ctor, …args) {

if (typeof ctor !== ‘function’) {

throw new TypeError(‘Type Error’);

}

const obj = Object.create(ctor.prototype);

const res = ctor.apply(obj, args);

const isObject = typeof res === ‘object’ && res !== null;

const isFunction = typeof res === ‘function’;

return isObject || isFunction ? res : obj;

}

15.instanceof


instanceof运算符用于检测构造函数的prototype属性是否出现在某个实例对象的原型链上。

const myInstanceof = (left, right) => {

// 基本数据类型都返回false

if (typeof left !== ‘object’ || left === null) return false;

let proto = Object.getPrototypeOf(left);

while (true) {

if (proto === null) return false;

if (proto === right.prototype) return true;

proto = Object.getPrototypeOf(proto);

}

}

16.原型继承


这里只写寄生组合继承了,中间还有几个演变过来的继承但都有一些缺陷

function Parent() {

this.name = ‘parent’;

}

function Child() {

Parent.call(this);

this.type = ‘children’;

}

Child.prototype = Object.create(Parent.prototype);

Child.prototype.constructor = Child;

17.Object.is


Object.is解决的主要是这两个问题:

+0 === -0 // true

NaN === NaN // false

const is= (x, y) => {

if (x === y) {

// +0和-0应该不相等

return x !== 0 || y !== 0 || 1/x === 1/y;

} else {

return x !== x && y !== y;

}

}

18.Object.assign


Object.assign()方法用于将所有可枚举属性的值从一个或多个源对象复制到目标对象。它将返回目标对象(请注意这个操作是浅拷贝)

Object.defineProperty(Object, ‘assign’, {

value: function(target, …args) {

if (target == null) {

return new TypeError(‘Cannot convert undefined or null to object’);

}

// 目标对象需要统一是引用数据类型,若不是会自动转换

const to = Object(target);

for (let i = 0; i < args.length; i++) {

// 每一个源对象

const nextSource = args[i];

if (nextSource !== null) {

// 使用for…in和hasOwnProperty双重判断,确保只拿到本身的属性、方法(不包含继承的)

for (const nextKey in nextSource) {

if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {

to[nextKey] = nextSource[nextKey];

}

}

}

}

return to;

},

// 不可枚举

enumerable: false,

writable: true,

configurable: true,

})

19.深拷贝


递归的完整版本(考虑到了Symbol属性):

const cloneDeep1 = (target, hash = new WeakMap()) => {

// 对于传入参数处理

if (typeof target !== ‘object’ || target === null) {

return target;

}

// 哈希表中存在直接返回

if (hash.has(target)) return hash.get(target);

const cloneTarget = Array.isArray(target) ? [] : {};

hash.set(target, cloneTarget);

// 针对Symbol属性

const symKeys = Object.getOwnPropertySymbols(target);

if (symKeys.length) {

symKeys.forEach(symKey => {

if (typeof target[symKey] === ‘object’ && target[symKey] !== null) {

cloneTarget[symKey] = cloneDeep1(target[symKey]);

} else {

cloneTarget[symKey] = target[symKey];

}

})

}

for (const i in target) {

if (Object.prototype.hasOwnProperty.call(target, i)) {

cloneTarget[i] =

typeof target[i] === ‘object’ && target[i] !== null

? cloneDeep1(target[i], hash)
target[i];

}

}

return cloneTarget;

}

20.Promise


// 模拟实现Promise

// Promise利用三大手段解决回调地狱:

// 1. 回调函数延迟绑定

// 2. 返回值穿透

// 3. 错误冒泡

// 定义三种状态

const PENDING = ‘PENDING’; // 进行中

const FULFILLED = ‘FULFILLED’; // 已成功

const REJECTED = ‘REJECTED’; // 已失败

class Promise {

constructor(exector) {

// 初始化状态

this.status = PENDING;

// 将成功、失败结果放在this上,便于then、catch访问

this.value = undefined;

this.reason = undefined;

// 成功态回调函数队列

this.onFulfilledCallbacks = [];

// 失败态回调函数队列

this.onRejectedCallbacks = [];

const resolve = value => {

// 只有进行中状态才能更改状态

if (this.status === PENDING) {

this.status = FULFILLED;

this.value = value;

// 成功态函数依次执行

this.onFulfilledCallbacks.forEach(fn => fn(this.value));

}

}

const reject = reason => {

// 只有进行中状态才能更改状态

if (this.status === PENDING) {

this.status = REJECTED;

this.reason = reason;

// 失败态函数依次执行

this.onRejectedCallbacks.forEach(fn => fn(this.reason))

}

}

try {

// 立即执行executor

// 把内部的resolve和reject传入executor,用户可调用resolve和reject

exector(resolve, reject);

} catch(e) {

// executor执行出错,将错误内容reject抛出去

reject(e);

}

}

then(onFulfilled, onRejected) {

onFulfilled = typeof onFulfilled === ‘function’ ? onFulfilled : value => value;

onRejected = typeof onRejected === ‘function’? onRejected :

reason => { throw new Error(reason instanceof Error ? reason.message : reason) }

// 保存this

const self = this;

return new Promise((resolve, reject) => {

if (self.status === PENDING) {

self.onFulfilledCallbacks.push(() => {

// try捕获错误

try {

// 模拟微任务

setTimeout(() => {

const result = onFulfilled(self.value);

// 分两种情况:

// 1. 回调函数返回值是Promise,执行then操作

// 2. 如果不是Promise,调用新Promise的resolve函数

result instanceof Promise ? result.then(resolve, reject) : resolve(result);

})

} catch(e) {

reject(e);

}

});

self.onRejectedCallbacks.push(() => {

// 以下同理

try {

setTimeout(() => {

const result = onRejected(self.reason);

// 不同点:此时是reject

result instanceof Promise ? result.then(resolve, reject) : resolve(result);

})

} catch(e) {

reject(e);

}

})

} else if (self.status === FULFILLED) {

try {

setTimeout(() => {

const result = onFulfilled(self.value);

result instanceof Promise ? result.then(resolve, reject) : resolve(result);

});

} catch(e) {

reject(e);

}

} else if (self.status === REJECTED) {

try {

setTimeout(() => {

const result = onRejected(self.reason);

result instanceof Promise ? result.then(resolve, reject) : resolve(result);

})

} catch(e) {

reject(e);

}

}

});

}

catch(onRejected) {

return this.then(null, onRejected);

}

static resolve(value) {

if (value instanceof Promise) {

// 如果是Promise实例,直接返回

return value;

} else {

// 如果不是Promise实例,返回一个新的Promise对象,状态为FULFILLED

return new Promise((resolve, reject) => resolve(value));

}

}

static reject(reason) {

return new Promise((resolve, reject) => {

reject(reason);

})

}

static all(promiseArr) {

const len = promiseArr.length;

const values = new Array(len);

// 记录已经成功执行的promise个数

let count = 0;

return new Promise((resolve, reject) => {

for (let i = 0; i < len; i++) {

// Promise.resolve()处理,确保每一个都是promise实例

Promise.resolve(promiseArr[i]).then(

val => {

values[i] = val;

count++;

// 如果全部执行完,返回promise的状态就可以改变了

if (count === len) resolve(values);

},

err => reject(err),

);

}

})

}

static race(promiseArr) {

return new Promise((resolve, reject) => {

promiseArr.forEach(p => {

Promise.resolve§.then(

val => resolve(val),

err => reject(err),

)

})

})

}

}

21.Promise.all


Promise.all是支持链式调用的,本质上就是返回了一个Promise实例,通过resolvereject来改变实例状态。

Promise.myAll = function(promiseArr) {

return new Promise((resolve, reject) => {

const ans = [];

let index = 0;

for (let i = 0; i < promiseArr.length; i++) {

promiseArr[i]

.then(res => {

ans[i] = res;

index++;

if (index === promiseArr.length) {

resolve(ans);

}

})

.catch(err => reject(err));

}

})

}

22.Promise.race


Promise.race = function(promiseArr) {

总结

  • 框架原理真的深入某一部分具体的代码和实现方式时,要多注意到细节,不要只能写出一个框架。

  • 算法方面很薄弱的,最好多刷一刷,不然影响你的工资和成功率😯

  • 在投递简历之前,最好通过各种渠道找到公司内部的人,先提前了解业务,也可以帮助后期优秀 offer 的决策。

  • 要勇于说不,对于某些 offer 待遇不满意、业务不喜欢,应该相信自己,不要因为当下没有更好的 offer 而投降,一份工作短则一年长则 N 年,为了幸福生活要慎重选择!!!

    开源分享:【大厂前端面试题解析+核心总结学习笔记+真实项目实战+最新讲解视频】

喜欢这篇文章文章的小伙伴们点赞+转发支持,你们的支持是我最大的动力!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值