通过举例和实际例子来加深前端的概念形式

1. 手写reduce
用法:

// 手写 reduce const a = [1, 3, 6, 8] const sum = a.reduce((accu, curr) => accu + curr, 0) console.log('sum', sum )
在注释中解释 reduce 的手写方法
// 1. 明确参数累加函数,接受两个参数,回调函数和初始值 const sum = a.reduce((accu, curr) => accu + curr, 0) console.log('sum', sum ) // 用原型的方式来定义方法 Array.prototype.myReduce = function(callback, initialValue) { // 分清可能的边界情况 if(typeof callback !== 'function') { throw `${callback} is not a function` } // 如果没有定义 initialValue的话,初始为 0 initialValue = initialValue ? initialValue : 0 // reduce本质上是遍历数组的参数, this为调用的数组 let arr = this // 定义最后返回的累加值 let result = initialValue for(let i = 0 ; i accu + curr, 0) console.log('sum', sum2 )
2. 手写链式方法
题目
手写 LazyMan ,实现 sleep 和 eat 两个方法,支持链式调用。 代码示例:
const me = new LazyMan('tom') me.eat('苹果').eat('香蕉').sleep(5).eat('葡萄') // 打印结果如下: // 'tom eat 苹果' // 'tom eat 香蕉' // (等待 5s) // 'tom eat 葡萄'
题目分析:用 taskQueue来实现或者或 Promise
class LazyMan { constructor(name) { this.name = name this.promiseChain = Promise.resolve() } sleep(second) { this.promiseChain = this.promiseChain.then(() => { return new Promise((resolve, reject) => { setTimeout(() => { resolve() }, second * 1000) }) }) return this } eat(name) { this.promiseChain = this.promiseChain.then(() => { return new Promise((resolve, reject) => { resolve() console.log(`${this.name} eat ${name}`) }) }) return this } }
用 Promise实现
class LazyMan { constructor(name) { this.name = name this.promiseChain = Promise.resolve() } sleep(second) { this.promiseChain = this.promiseChain.then(() => { return new Promise((resolve, reject) => { setTimeout(() => { resolve() }, second * 1000) }) }) return this } eat(name) { this.promiseChain = this.promiseChain.then(() => { return new Promise((resolve, reject) => { resolve() console.log(`${this.name} eat ${name}`) }) }) return this } }
3. 数组转树/树转数组
数组转树:文件列表是树形结构的时候,可能会遇到数组转树的情况
思路:首先定义一个 data 来生成一个 id 和对象的键值对的形式,然后用一个 result 来生成结果
function arrayToTree(arr) { let data = {}, result = []; arr.map((item)=> data[item.id] = item) for(let arritem of data) { if(arritem.parentId) { if(data[arritem.parentId].children { data[arritem.parentId].children = [] } data[arritem.parentId].children.push(arritem) } else { result.push(arritem) } }
树转数组:类似二叉树的层序遍历
4.ES6新特性
https://juejin.cn/post/6844903959283367950
1)var, const, let区别
2)Map和 Set
- 集合(Set) 和数组的区别
- Map和对象的区别
实际应用场景:深入浅出JS—13 Set和Map应用场景_jsmap数据结构的使用场景-CSDN博客
3) WeakMap和 WeakSet
5.闭包
定义:在一个函数中可以访问另一个函数中的变量
题目:
// 实现如下代码,只打印出 3 次前的调用的值 var vote = before(3, fn) vote('tom') vote('alice') vote('carm') vote('car') vote('cai') vote('ca2')
解法及讲解:
const before = (n , fn) => { let times = 0 return function(...args) { if(times { console.log(`This is ${name}`) }) vote('tom') vote('alice') vote('carm') vote('car') vote('cai') vote('ca2')
1)在外部函数定义了一个 times 的变量,新生成的函数没有自己的变量,它可以访问外部函数的变量,词法作用域根据源代码中声明变量的位置来确定该变量在何处可用
2)vote作为一个外部函数来返回了这个定义的函数,JS 函数形成闭包,闭包是由函数以及声明该函数的词法环境组合而成的,该环境包含了这个闭包创建时的任何局部变量,vote为返回函数的引用,返回函数维护了一个词法环境,所以 vote 被调用时,times 依然可用
3)如果要传入参数,即在返回的函数的参数中去实现这个参数
实际应用:
1)为响应事件而执行的函数
2)闭包模拟私有方法
在其他函数中创建函数其实是不明智的,创建新的对象或类时,应该关联于对象的原型,而不是对象的构造器中
参考:闭包 - JavaScript | MDN
6. Promise
用 Promise来实现具体例子,手写 Promise.all等方法
1) 实现一个 sleep 函数,实现如下条件
const testSleep = async () => { const currentTime = Date.now() await sleep(1000) console.log(Date.now() - currentTime) } testSleep()
知识点 1:事件循环
先执行同步任务,再执行宏任务,再执行所有的微任务,再执行一个宏任务,再执行所有的微任务
宏任务有:
微任务有:
(async () => { console.log(1); setTimeout(() => { console.log(2); }, 0); await new Promise((resolve, reject) => { console.log(3); }).then(() => { console.log(4); }); console.log(5); })();
参考:牛客最新前端 JS 笔试百题
以上程序的输出结果是什么?
输出结果是 1,3,Promise(pending), 2, 这里 async 里的内容应该执行,await 之后的内容应该等 await 有返回值后再执行,但是 promise 并没有产生 resolve 或是 reject 的结果,所以是 pending 状态,await 之后的值也不会执行
知识点 1.1 异步函数的解决方案
如果是同步代码,需要暂停等待返回值,而异步代码不需要暂停等待返回值,而是立即执行后面的代码,服务器返回信息后再执行回调函数
知识点 1.2 Promise和 async/await区别
1.ES6/ES7的区别
2. await 是写法上和同步状态类似
sleep解法
const sleep = (times) => { return new Promise((resolve) => { setTimeout(() => { resolve() }, times) }) }
这里await等待 promise 返回成功的值,然后再执行后面的函数
知识点 2: Promise 的解决方法
Promise是在处理多个异步任务后的结果, 参数是 promise 数组,返回值是 promise结果
Promise.all()
Promise.race()
Promise.allSettled()
手写 Promise.all()
PromiseMyAll = (promises) => { // return a Promise return new Promise((resolve, reject) => { const result = []; let promiseCount = 0; promises.forEach((promiseItem) => { // Resolve the given value Promise.resolve(promiseItem) .then((res) => { result[promiseCount] = res; promiseCount = promiseCount + 1; if (promiseCount === promises.length) { // 这里是定义 Promise 来生成的 resolve(result); } }) .catch((err) => reject(err)); }); }); };
7. 深拷贝和浅拷贝
浅拷贝:对基础数据类型的准确拷贝,对复杂数据类型只拷贝第一层
深拷贝:对基础数据类型还是复杂数据类型都是准确拷贝
题目:
let obj = { name: '祁纤', person: [20, '男', { demo: { name: '沉香', age: '18' } }, null], obj: { sex: '男', age: 20, bar: ['red', 'bule'] } } let bar = {} deepClone(obj, bar) bar.person.push('我@bar变了') console.log('@bar', bar) console.log('@obj', obj)
for...in 是可枚举对象,for..of..是可迭代对象
深拷贝的实现代码:
const deepClone = (originObj, copiedObj = {}) => { if (Array.isArray(originObj)) { copiedObj = []; } for (let key in originObj) { if (originObj.hasOwnProperty(key)) { if (typeof originObj[key] === "object") { copiedObj[key] = deepClone( originObj[key], Array.isArray(originObj[key]) ? [] : {} // 有可能是 array或是 object,因为复杂数据类型的 typeof都是 object ); } else { copiedObj[key] = originObj[key]; } } } return copiedObj; };