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

时间:2019-05-09 04:30:33

标签: javascript arrays recursion ecmascript-6 ecmascript-5

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

我可以用Python做到:

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

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

5 个答案:

答案 0 :(得分:1)

首先,您必须知道arrays具有.length属性。知道这一点,并且如果您仍然想通过递归获得它,那么我将执行类似下一个的操作,即使用iteratorArray.slice()。这种方法避免使用.length属性来检测停止条件。

const count = (list) =>
{
    let ite = list[Symbol.iterator]();

    if (ite.next().done)
        return 0;
    else
        return 1 + count(list.slice(1));
}

console.log(count([]));
console.log(count([undefined, null]));
console.log(count([1, 2, undefined, 3, 4]));
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}

答案 1 :(得分:1)

ES6递归函数:

const count = arr => arr[0] == undefined ? 0 : 1 + count(arr.slice(1));
console.log(count([1, 2, 3]));
console.log(count([]));

ES5:

function count(arr) {
  return arr[0] == undefined ? 0 : 1 + count(arr.slice(1));
}
console.log(count([1, 2, 3]));
console.log(count([]));

答案 2 :(得分:1)

最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]));

答案 3 :(得分:0)

计数元素是荒谬的,因为您只能使用length属性。它将是O(1)并完成您的期望。至于对元素求和或做某事:

 
// recursively. Works only on arrays 
const sumElements = (arr) => {
  if (arr.length === 1) return arr[0];

  const [e, ...rest] = arr;
  return e + sumElements(rest);
}


// recursively and effiecent. Works only on arrays
const sumElements = (arr) => {
  const helper = (index, acc) => index < 0 ? acc helper(index - 1, acc + arr[index]);
  return helper(arr.length-1, 0);
}


// using higher order functions. Works for all collections that has reduce defined
const sumElements = list => list.reduce((acc, e) => acc + e), 0);

// using iterators. Works for all collections that has iterator defined
const sumElements = (list) => {
  let sum = 0;
  for (const e of list) {
    sum += e;
  }
  return sum;
}

答案 4 :(得分:0)

这是两个解决方案。

const count1 = ([x, ...xs]) => x ? 1 + count1(xs) : 0
const count2 = (xs) => xs.reduce((y) => y + 1, 0)

console.log(count1([1, 2, 3, 4, 5]))
console.log(count2([1, 2, 3, 4, 5]))