1. 手动实现数组的reduce方法
// 修改原型方法Array.prototype.reduce = function(fn, init) { if (init === undefined && !this.length) throw new Error('error') let res = init ? init : this[0] for (let i = init ? 0 : 1; i < this.length; i++) { console.log('执行') res = fn(res, this[i], i, this) } return res}// 使用class创建自定义类型class MyReduce { constructor(arr, init) { this.arr = arr this.init = init } reduce(fn) { if (this.init === undefined && !this.arr.length) throw new Error('error') let res = this.init ? this.init : this.arr[0] for (let i = this.init ? 0 : 1; i < this.arr.length; i++) { console.log('myreduce') res = fn(res, this.arr[i], i, this.arr) } return res }}// 验证结果let arr = [1,2,3,4,5]// let res = arr.reduce((pre, cur) => {// return pre + cur// })let myreduce = new MyReduce(arr)let res = myreduce.reduce((pre, cur) => { return pre + cur})console.log(res)
2. 手动实现数组的some、every、filter、forEach、map
Array.prototype.some = function(fn) {
let len = this.length
for (let i = 0; i < len; i++) {
if (fn(this[i], i, this)) {
return true
}
}
return false
}
let arr = [1,2,3,4,5]
console.log(arr.some(item => item > 5))
3. 手动实现数组的sort方法
// sort优化: 无法隐式转换为数字的数据会导致排序失败
// sort排序时是通过比较数组项的第一个字符串的ASCLL码的大小顺序排序的
const sort = arr => arr.sort((a,b) => a - b) // 顺序
const sort = arr => arr.sort((a,b) => b - a) // 逆序
// 冒泡
Array.prototype.sort = function() {
let arr = this
let len = arr.length
for (let i = 0; i < len - 1; i++) {
for (let j = 0; j < len - 1 - i; j++) {
if (arr[j] > arr[j+1]) {
[arr[j], arr[j+1]] = [arr[j+1], arr[j]]
}
}
}
return arr
}
4. 手动实现applay、call、bind方法
// apply和call类似
Function.prototype.call = function(obj, ...args) {
const fn = Symbol('fn')
const newobj = obj || window
newobj[fn] = this
const res = newobj[fn](...args)
delete newobj[fn]
return res
}
// bind方法
Function.prototype.bind = function(obj, ...args1){
return (...args2) => {
const fn = Symbol('fn')
obj[fn] = this
obj[fn](...args1,...args2)
delete obj[fn]
}
}
5. 数组的扁平化(flat)
// 本质就是把内部的【】去掉,方法多样
// ES6
const flat = arr => arr.toString().split(',').map(item => +item)
// 循环:略
6. 手动实现Promise的all和race方法
// 1. Promise.all方法
Promise.all = function (promiseArr) {
let result = []
return new Promise((resolve, reject) => {
promiseArr.forEach(item => {
item.then(res => result.push(res)).catch(e => rejcect(e))
})
return resolve(result)
})
}
// 2. Promise.race方法
7. 使用 setTimeout 写一个 setInterval
const mySetInterval = (callback, time) => {
(function inner() {
const timer = setTimeout(() => {
callback()
clearTimeout(timer)
inner()
}, time)
})()
}
8. 快速创建1-100的数组
const arr = Array.from(Array(100), (item, index) => index + 1)
9. 实现模板字符串