Last active
September 12, 2019 03:02
-
-
Save lorainwings/7892f9619b2395a2fc6262489c8ee776 to your computer and use it in GitHub Desktop.
对象和数组通用forEach
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function forEach(target, iteratee) { | |
const array = Array.isArray(target) ? target : Object.keys(target); | |
let index = -1; | |
const length = array.length; | |
while (++index < length) { | |
const key = target !== array ? array[index] : index; | |
iteratee(target[key], key); | |
} | |
return target; | |
} | |
//使用方式 | |
const target = [1,3,4]; | |
const target1 = {a:'2',b:'3'}; | |
forEach(target,(value,key)=>{ | |
console.log(value,key) | |
}) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment