对象遍历的几种方式
for in
const obj = {name: 'wsf', age: 12, sex: '男'}
for(const key in obj) {
console.log(obj[key], key, obj)
}
Object.keys
const obj = {name: 'wsf', age: 12, sex: '男'}
Object.keys(obj).forEach(key => {
console.log(obj[key], key, obj)
})
自定义 forEach 方法
Object.prototype.forEach = function forEach(fn){
for (const key in this){
if(Object.prototype.hasOwnProperty.call(this, key)) {
fn.call(null, this[key], key, this)
}
}
}
const obj = {name: 'wsf', age: 12, sex: '男'}
obj.forEach((val, key, obj) => {
console.log(val, key, obj)
})
Array & Object forEach
function isArray(ele) {
return Object.prototype.toString.call(ele) === "[object Array]"
}
function isObject(ele) {
return Object.prototype.toString.call(ele) === "[object Object]"
}
function forEach(obj, fn) {
if (isArray(obj)) {
obj.forEach((ele, index, array) => fn.call(null, ele, index, array))
} else if (isObject(obj)) {
for (const key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
fn.call(null, obj[key], key, obj)
}
}
} else {
return
}
}
const obj = {name:'wsf', age: 19, sex: '男'}
forEach(obj, (val, key, obj) => {
console.log(val, key, obj)
})
const array = [1,2,3]
forEach(array, (val, index, array) => {
console.log(val, index, array)
})