前端面试手写题系列 V
前端面试 手写题系列 已经完结,包含了以下的题目:
手写拍平数组 flat 手写防抖和节流函数 手写深拷贝 手写快排 手写 call、apply、bind 手写一个 sleep 函数 手写冒泡排序 函数柯里化 对象扁平化 手写 new 过程 求数组中的最大值 手写 instanceof 手写 foreach 函数 手写迭代器 手写 filter 实现一个 compose 函数 正则相关(去哪儿原题) 实现一个任务调度函数(得物原题) 数组转化为 tree 不使用 a 标签,实现 a 标签的功能 手写插入排序 LRU 算法 归并排序 求两个数组的交集、并集、补集、差集 提取 url 中的参数 实现一个洗牌函数 shuffle 希尔排序
1.手写 foreach 函数
手写 foreach 函数:遍历执行函数
// 手写 forEach
Array.prototype.myForEach = function (fn) {
if (typeof fn !== 'function') {
throw new Error('请传入一个函数')
}
for (let i = 0; i < this.length; i++) {
// 第一个参数是 this 的指向,第二个参数是传给 fn 的参数值
fn.call(this, this[i])
}
}
const arr = [1, 2, 3]
arr.myForEach(item => {
console.log(item + 1)
})
控制台:
PS C:\Users\wy151\Desktop\demo> node demo.js
2
3
4
2.手写迭代器
在 JavaScript 中,迭代器是一个对象,它定义一个序列,并在终止时可能附带一个返回值。
更具体地说,迭代器是通过使用 next() 方法实现了迭代器协议的任何一个对象,该方法返回具有两个属性的对象:
- value:即迭代序列的下一个值
- done:如果已经迭代到序列中的最后一个值,则它为 true。如果 value 和 done 一起出现,则它就是迭代器的返回值
一旦创建,迭代器对象可以通过重复调用 next() 显式地迭代。迭代一个迭代器被称为消耗了这个迭代器,因为它通常只能执行一次:在产生终值后,对 next() 的额外调用应该继续返回 {done:true}。
//手写迭代器
function myGenerator(arr) {
// 这个对象中包含两个属性:值 + 是否迭代完成
let index = 0;
return {
next: function () {
return index < arr.length ? {
value: arr[index++],
done: false
} : {
value: undefined,
done: true
};
}
}
}
let gen = myGenerator([1, 2]);
console.log(gen.next());
console.log(gen.next());
console.log(gen.next());
控制台:
PS C:\Users\wy151\Desktop\demo> node demo.js
{ value: 1, done: false }
{ value: 2, done: false }
{ value: undefined, done: true }
3.手写 filter
作用:
filter的基本功能是遍历一个数组,并返回一个符合过滤条件的新数组且不改变原有数组。
// 语法: arr.filter(function(currentVal, index, arr),thisVal)
//手写filter
//把filter方法挂载到Array构造函数的原型上来模拟
Array.prototype.myFilter = function (func, thisVal) {
//判断第一个参数是否为函数
if (typeof func !== 'function') return '请输入一个函数';
//确定回调函数的this指向
let arr = this;
//定义返回值
let filterArr = [];
//对数组进行遍历
for (let i = 0; i < arr.length; i++) {
let temp = func.call(thisVal, arr[i]);
if (temp) {
filterArr.push(arr[i]);
}
}
return filterArr;
}
//测试用例
let arr = [1, 2, 3, 4, 5]
let res = arr.myFilter(item => item !== 1) // 这里并没有写第二个参数,thisVal
console.log(res);
控制台:
PS C:\Users\wy151\Desktop\demo> node demo.js
[ 2, 3, 4, 5 ]
手写题系列文章
前端手写题系列 I
前端手写题系列 II
前端手写题系列 III
前端手写题系列 IV
前端手写题系列 V
前端手写题系列 VI
前端手写题系列 VII
前端手写题系列 VIII
前端手写题系列 IX
前端手写题系列 X