企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
[toc] #### 1.手写 forEach forEach((item, index, arr)),无返回值 ```js Array.prototype.mForEach = function (calback) { for (let i = 0; i < this.length; i++) { calback(this[i], i, this); } }; ``` #### 2.手写 map map((item, index, arr)),返回新数组 ```js Array.prototype.mMap = function (callback) { let res = []; for (let i = 0; i < this.length; i++) { res.push(callback(this[i], i, this)); // 每次都往 res push callback的返回值 } return res; }; ``` #### 3.手写filter filter 返回所有满足条件的值 ```js // filter Array.prototype.mFilter = function (callback) { let res = []; for (let i = 0; i < this.length; i++) { callback(this[i], i, this) && res.push(this[i]); } return res; }; ``` #### 4.手写every 全部满足则返回true,有一项不满足则return false,中断遍历 ```js Array.prototype.mEvery = function (callback) { for (let i = 0; i < this.length; i++) { if (!callback(this[i], i, this)) { return false; } } return true; }; ``` #### 5.手写some 只要有一个为 true ,则返回 true,中断 ```js Array.prototype.mSome = function (callback) { for (let i = 0; i < this.length; i++) { if (callback(this[i], i, this)) return true; } return false; }; ``` #### 6.手写 find 找到第一位 ```js Array.prototype.mFind = function (callback) { for (let i=0; i<this.length; i++) { if(callback(this[i], i, this)) return this[i] } } ``` #### 7.手写 findIndex 找到第一位的index ```js Array.prototype.mFindIndex = function (callback) { for (let i=0; i<this.length; i++) { if(callback(this[i], i, this)) return i } } ``` #### 8.手写reduce cur 从第一项开始 每次将 callback 中的返回值作为下一次的 pre 如果传了第二个参数,则 pre 从传的参开始, cur 从第0项开始 如果没传第二个参数,则 pre 从第0项开始,cur 从第0项开始 返回最终的 pre ```js Array.prototype.mReduce = function (callback, ...args) { let start = 0 prev = null if (args.length === 0) { prev = this[0] start = 1 } else { pre = args[0] } for (let i=start; i<this.length; i++) { prev = callback(prev, this[i], i, this) } return prev } ``` #### 9.手写fill fill(value, start, end) 会修改原数组,也会返回新数组 如果end为负数,则表示倒数第几位 ```js Array.prototype.mFill = function (initValue, start=0, end=this.length) { // 从倒数开始 if (end < 0) { end = this.length + end } for (let i=start; i<end; i++) { this[i] = initValue } return this } ``` #### 10.join ```js Array.prototype.mJoin = function(s = ',') { let str = '' for(let i=0; i<this.length; i++) { if (i === this.length - 1) { str = str + this[i] } else { str = str + this[i] + s } } return str } ``` #### 11.拍平 flat ```js let arr = [1, 2, [3, 4], [5, 6, [7, 8]]]; Array.prototype.mFlat = function (num = Infinity) { let arr = this let i = 0 // 展开层级 while(arr.some(item => Array.isArray(item))) { arr = [].concat(...arr) i++ if (i>=num) { break } } return arr } ```