源码实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| function myForEach(arr, callback) { let T, k; if(arr === null) { throw new TypeError('this is null or not defined'); } const O = Object(arr); const len = O.length >>> 0; if(typeof callback !== 'function') { throw new TypeError(`${callback} is not a function`); } if(arguments.length > 1) { T = callback; } k = 0; while (k < len) { if(k in O) { const kValue = O[k]; callback.call(T, kValue, k, O); } k++; } return undefined; } const test = [1,2,,3]; myForEach(test, (item) => { console.log(item); })
|
技能点
1、无符号右移:将对应数转化为二进制,接着向右移位得到的数值。
1 2
| const oldValue = 64; const newValue = oldValue >>> 5;
|
2、使用技巧:转化数据(数值不变,其他的类型全部转化为0)
1 2 3 4
| 1 >>> 0 undefined >>> 0 null >>> 0 string' >>> 0 // 0
|
注意事项
1、async await的语法糖不起作用:由于其内部封装并调用了回调函数,因此就算用了async await也不起作用。
2、无法随时退出循环:不能使用break/continue的方式退出或中断循环,因为其内部使用while循环。