[我想知道是否存在一种/简单的方法来使用全局JavaScript Array
对象的方法,例如Array.prototype.map
对象上的Array.prototype.reduce
,Array.prototype.filter
甚至是Iterables
。或至少不需要创建临时数组。
我已经在Mozilla网站,StackOverflow,Google,GitHub等上进行了搜索,但是没有找到任何答案。
实际示例:
假设我要计算从sum
到某个数字“ 1
”(例如num
)的所有数字的10
。
我在想
Iterator
/ Generator function
来获得所需的数字,一一(在下面的示例中为Generator
)Array.prototype.reduce()
之类的方法对其进行总结。这对我来说是可行的,因为这类方法(reduce
)一次使用一个值,然后在操作完成时要求下一个值,这与Streams
中的Java
非常相似。这正是Iterable
的功能。
mySum(10); // returns 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55
/**
* Sums all the number from 1 to the provided number
* @param num {number} the maximum number to include in the sum
* @returns the sum of all numbers from 1 to the provided number
*/
function mySum(num) {
function* myGenerator() {
for(let i = 1; i <= num; ++i) {
yield i;
}
}
return myGenerator().reduce((previous, current) => previous + current, 0);
}
上面的这段代码显然不起作用,因为Iterable
没有reduce
方法。但是为什么迭代器没有一个?
是否有避免像下面这样创建临时数组的方法?
mySum(10); // returns 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55
/**
* Sums all the number from 1 to the provided number
* @param num {number} the maximum number to include in the sum
* @returns the sum of all numbers from 1 to the provided number
*/
function mySum(num) {
function* myGenerator() {
for(let i = 1; i <= num; ++i) {
yield i;
}
}
return Array.from(myGenerator()).reduce((previous, current) => previous + current, 0); // notice here the change
}
不确定这是best的方式(我的生成器经验有限)-但是这种方式没有临时数组
function mySum(num) {
function* myGenerator() {
for(let i = 1; i <= num; ++i) {
yield i;
}
}
let sum = 0;
const gen = myGenerator();
let value, done;
while(({value, done} = gen.next()) && !done) {
sum += value;
}
return sum;
}
console.log(mySum(10));