UNPKG

wft-utils

Version:

The commonly used tool functions in daily development

101 lines (95 loc) 2.52 kB
// 手写forEach,该方法是要挂载到Array上的原型上,其中this指向调用者,即当前数组 function myForEach(fn) { if (typeof fn !== 'function') { return } for (let i = 0; i < this.length; i++) { fn.call(this, this[i], i, this) } } // 手写map方法,该方法挂载到Array上的原型上,其中this指向调用者,即当前数组 function myMap(fn) { if (typeof fn !== 'function') { return [] } const target = [] for (let i = 0; i < this.length; i++) { let ret = fn.call(this, this[i], i, this) target.push(ret) } return target } // 手写filter方法,将该方法挂载到Array原型上,其中this指向调用者,即当前数组 function myFilter(fn) { if (typeof fn !== 'function') { return [] } const target = [] for (let i = 0; i < this.length; i++) { let ret = fn.call(this, this[i], i, this) if (ret) { target.push(this[i]) } } return target } // 手写every方法,将该方法挂载到Array原型上,其中this指向调用者,即当前数组 function myEvery(fn) { if (typeof fn !== 'function') { return false } let target = true for (let i = 0; i < this.length; i++) { let ret = fn.call(this, this[i], i, this) if (!ret) { target = false break } } return target } // 手写some方法,将该方法挂载到Array原型上,其中this指向调用者,即当前数组 function mySome(fn) { if (typeof fn !== 'function') { return false } let target = false for (let i = 0; i < this.length; i++) { let ret = fn.call(this, this[i], i, this) if (ret) { target = true break } } return target } // 手写find方法,将该方法挂载到Array原型上,其中this指向调用者,即当前数组 function myFind(fn) { if (typeof fn !== 'function') { return } let target for (let i = 0; i < this.length; i++) { let ret = fn.call(this, this[i], i, this) if (ret) { target = this[i] break } } return target } // 手写findIndex方法,将该方法挂载到Array原型上,其中this指向调用者,即当前数组 function myFindIndex(fn) { if (typeof fn !== 'function') { return } let targetIndex for (let i = 0; i < this.length; i++) { let ret = fn.call(this, this[i], i, this) if (ret) { targetIndex = i break } } return targetIndex }