初始值:
var obj = {
a: 1,
b: 2,
c: 3,
d: 4,
e: 5,
};
第一种:for in
for (let key in obj) {
console.log(key + ":" + obj[key]);
}
第二种:Object.keys 获取key
Object.keys(obj).forEach((key) => {
console.log(key + ":" + obj[key]);
});
第三种:Object.keys 获取key Object.values 获取value (第二种类似)
for (let key in obj) {
console.log(key + ":" + obj[key]);
}
第四种:Object.entries 搭配 for-of
for (let [key, value] of Object.entries(obj)) {
console.log(key + ":" + value);
}
第五种:Object.getOwnPropertyNames(obj) 返回数组
Object.getOwnPropertyNames(obj).forEach((key) => {
console.log(key + ":" + obj[key]);
});
第六种:Reflect.ownKeys(obj) 返回数组
Reflect.ownKeys(obj).forEach((key) => {
console.log(key + ":" + obj[key]);
});