Skip to content

Instantly share code, notes, and snippets.

@lorainwings
Last active September 12, 2019 03:02
Show Gist options
  • Save lorainwings/7892f9619b2395a2fc6262489c8ee776 to your computer and use it in GitHub Desktop.
Save lorainwings/7892f9619b2395a2fc6262489c8ee776 to your computer and use it in GitHub Desktop.
对象和数组通用forEach
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