JavaScript 对象迭代

本文详细探讨了JavaScript中对象的迭代机制,包括如何使用for...in循环,Symbol.iterator以及ES6引入的Map和Set的迭代。同时,还讨论了如何自定义对象的迭代行为以及在实际开发中的应用案例。
摘要由CSDN通过智能技术生成
遍历自身属性遍历继承属性遍历不可枚举属性遍历 Symbol 类型属性
Object.getOwnPropertyNames(obj)
Object.getOwnPropertyDescriptor(obj, prop)
Object.getOwnPropertyDescriptors(obj)
Object.getOwnPropertySymbols(obj)
Object.keys(obj)
Reflect.ownKeys(target)
obj.hasOwnProperty(prop)
for-in
function ParentClass() {
  this.foo = 'foo';
}
ParentClass.prototype.inheritedMethod = function() {};

function ChildClass() {
  this.bar = 'bar';
  this.method = function() {};
}

ChildClass.prototype = new ParentClass;
ChildClass.prototype.prototypeMethod = function() {};

var obj = new ChildClass();

Object.defineProperty(obj, 'baz', {
  enumerable: false,
  configurable: false,
  writable: false,
  value: 'baz'
});

var quxSymbol = Symbol();

Object.defineProperty(obj, quxSymbol, {
  enumerable: false,
  configurable: false,
  writable: false,
  value: 'qux symbol'
});

Object.keys(obj); // ["bar", "method"]
Object.getOwnPropertyNames(obj); // ["bar", "method", "baz"]
Reflect.ownKeys(obj); // ["bar", "method", "baz", Symbol()]

let arr = []; for (const item in obj) { arr.push(item) } // ["bar", "method", "foo", "prototypeMethod", "inheritedMethod"]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值