对象遍历与常用方法
约 378 字大约 1 分钟
2026-02-26
对象操作里最常见的问题是:
- 我到底在遍历“自身属性”还是“原型链属性”?
- 我拿到的是 key、value 还是 entry?
遍历与判断
for...in
会遍历对象可枚举属性(包含原型链上的可枚举属性)。
const parent = { p: 1 }
const obj = Object.create(parent)
obj.a = 10
for (const k in obj) {
console.log(k) // a, p
}hasOwnProperty / Object.hasOwn
用于判断是否是对象自身属性。
for (const k in obj) {
if (Object.prototype.hasOwnProperty.call(obj, k)) {
console.log(k) // a
}
}in
会检查“对象自身 + 原型链”。
console.log('a' in obj) // true
console.log('p' in obj) // true
console.log(Object.prototype.hasOwnProperty.call(obj, 'p')) // falseinstanceof
检查某构造函数的 prototype 是否在对象原型链上。
function A() {}
const a = new A()
console.log(a instanceof A) // true
console.log(a instanceof Object) // true常用对象 API
Object.keys / values / entries
const user = { name: 'Tom', age: 18 }
console.log(Object.keys(user)) // ['name', 'age']
console.log(Object.values(user)) // ['Tom', 18]
console.log(Object.entries(user)) // [['name', 'Tom'], ['age', 18]]Object.assign
const target = { a: 1 }
const source = { b: 2 }
const result = Object.assign(target, source)
console.log(result) // { a: 1, b: 2 }
console.log(result === target) // true注
Object.assign 是浅拷贝,嵌套引用仍然共享。
Object.create
const base = { role: 'admin' }
const obj = Object.create(base)
console.log(obj.role) // adminObject.create(null) 可创建“无原型字典对象”(无继承属性,适合做纯 map)。
Object.prototype.toString.call
console.log(Object.prototype.toString.call([])) // [object Array]
console.log(Object.prototype.toString.call({})) // [object Object]
console.log(Object.prototype.toString.call(new Date())) // [object Date]链式调用
链式调用的核心是每步都返回 this。
const sched = {
morning() {
console.log('Go shopping')
return this
},
noon() {
console.log('Having a rest')
return this
},
evening() {
console.log('Walking')
return this
},
}
sched.morning().noon().evening()