JS中数字原型的自定义迭代器 [英] Custom Iterator for Number Prototype in JS
问题描述
最近我了解了JS迭代器,用于中的(of)
循环。因为在JS中,甚至原语都有原型,我想知道是否可以扩展Number原型,以便以下是一个有效的表达式:
Recently I learned about JS iterators, beeing used in a for( of )
loops. Since in JS even primitives have a prototype, I wondered if it is possible to extend the Number prototype so that the following would be a valid expression:
for(let i of 10) console.log(i); //0 1 2 3 4 5 6 7 8 9
显然这只适用于整数,但是有没有办法实现这个?
Obviously this would only work for integers, but is there a way to implement this?
希望有,但我自己无法创建这个,因为我是JS的这一部分的新手......
Hopefully there is, but I wasn't able to create this myself since I'm new to this part of JS...
推荐答案
你可以采取 Generator
/ en-US / docs / Web / JavaScript / Reference / Global_Objects / Symbol / iteratorrel =nofollow noreferrer> Symbol.iterator
作为<的原型数字
。
Number.prototype[Symbol.iterator] = function* () {
for (var i = 0; i < this; i++) {
yield i;
}
};
console.log([...10]);
.as-console-wrapper { max-height: 100% !important; top: 0; }
这篇关于JS中数字原型的自定义迭代器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!