gpt4 book ai didi

Javascript:递归计算数组中所有元素的总和?

转载 作者:行者123 更新时间:2023-11-30 07:49:20 24 4
gpt4 key购买 nike

我正在尝试编写一个递归函数来使用 Javascript 计算数组中的项目数。

我可以用 Python 来做:

def count(list):
if list == []:
return 0
return 1 + count(list[1:])

我如何在 ES5 和 ES6 中做到这一点?

最佳答案

最 es6-ish、fp-ish 的编写方式。适用于所有可迭代对象。

const count = xs =>
xs[Symbol.iterator]().next().done
? 0
: 1 + (([,...xr]) => count(xr))(xs);

console.log(count([1,2,3]));
console.log(count("hello123"));
console.log(count({
*[Symbol.iterator]() {
yield 1;
yield 2;
yield 3;
yield 4;
}
}));
console.log(count([]));
console.log(count([1, undefined, 2]));

关于Javascript:递归计算数组中所有元素的总和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56052227/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com