说明
1、可迭代对象是实现了@@iterator方法的对象,那么可迭代对象就可以通过重写@@iterator方法实现自定义迭代行为。
@@iterator是一个可以返回迭代器对象的函数。
2、当next方法返回时,迭代结束。
实例
const arr = [1, 3, 5, 7]; arr[Symbol.iterator] = function () { const ctx = this; const { length } = ctx; let index = 0; return { next: () => { if (index < length) { return { value: ctx[index++] * 2, done: false }; } else { return { done: true }; } } }; }; [...arr]; // [2, 6, 10, 14]
以上就是js中自定义迭代行为的方法,希望对大家有所帮助。更多js学习指路:
推荐操作环境:windows7系统、jquery3.2.1版本,DELL G3电脑。
Copyright © 2019- net188.cn 版权所有 湘ICP备2022005869号-2
违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com
本站由北京市万商天勤律师事务所王兴未律师提供法律服务