简体   繁体   English

使用递归对数组中的元素求和,即使它们是字符串

[英]Sum of elements in array using recursion even if they are string

Have to create a function that return the sum of the element in the array but if the array is必须创建一个 function 返回数组中元素的总和,但如果数组是

["a","b","c"] // output : abc    

So far I have到目前为止我有

 function calculateSumRecursion(array) {
          //your code
          if (array.length === 0 ) {
            return 0
          }
          
      return array[0] + calculateSumRecursion(array.slice(1))
    }

I found out how to calculate the sum of all numbers using recursion but when it's an array of string like我发现了如何使用递归计算所有数字的总和,但是当它是一个字符串数组时

array = ["a","b","c"] 

it returns me它返回我

// abc0

because of the if statement.. is there any way to say因为 if 语句..有什么办法可以说

if (array.length === 0) return nothing instead of a 0 (that work only when it's an array of number?)

You just need to return the only value in the array when the length is 1, rather than waiting until you get a length of 0. That way you are always summing compatible types (numbers or strings).当长度为 1 时,您只需要return数组中的唯一值,而不是等到长度为 0 时才返回。这样,您总是对兼容类型(数字或字符串)求和。 Note that you still need a test for a 0 array length in case the function gets called with an empty array.请注意,如果使用空数组调用 function,您仍然需要对 0 数组长度进行测试。 In this case you need to choose what to return;在这种情况下,您需要选择要返回的内容; as requested, it is 0.根据要求,它是 0。

 function calculateSumRecursion(array) { if (array.length === 0) { return 0; } if (array.length === 1) { return array[0]; } return array[0] + calculateSumRecursion(array.slice(1)) } console.log(calculateSumRecursion([1, 2, 3, 4, 5])); console.log(calculateSumRecursion(['a', 'b', 'c'])); console.log(calculateSumRecursion([]));

let arr = [1,2,3,4,5] // output : abc
let sum = calculateSumRecursion(arr);

function calculateSumRecursion (arr) {
    return arr.length ? arr.pop() + calculateSumRecursion(arr) : 0;
}

Slice version切片版

let arr = [1,2,3,4,5] // output : abc
let sum = calculateSumRecursion(arr);

function calculateSumRecursion (arr) {
    return arr.length ? arr[0] + calculateSumRecursion(arr.slice(1)) : 0;
}

Return empty string on recursion base case.在递归基本情况下返回空字符串。 Just replace your return 0 to return '' .只需将您的return 0替换为return ''

 const array = ['a', 'b', 'c']; function calculateSumRecursion(array) { if (array.length === 0) { return ''; } return array[0] + calculateSumRecursion(array.slice(1)); } console.log(calculateSumRecursion(array));

If you are want to work with number also then check array length for zero as well as one.如果您还想使用数字,请检查数组长度为零还是一。

 const array = ['a', 'b', 'c', 'e']; const array2 = []; const array3 = [1, 2, 3]; function calculateSumRecursion(array) { const rec = array.length === 1? array[0]: array.length >= 1 && array[0] + calculateSumRecursion(array.slice(1)); return array.length === 0? 0: rec; } console.log(calculateSumRecursion(array)); console.log(calculateSumRecursion(array2)); console.log(calculateSumRecursion(array3));

Change return 0 to return "" which will add an empty string to the sum. return 0更改为return "" ,这将向总和添加一个空字符串。

You have returned 0 when the array is empty.当数组为空时,您返回了0

Now, you are doing string operations so it is needed to return empty value (not zero) so it will be affordable to return "" .现在,您正在执行字符串操作,因此需要返回空值(不是零),以便返回""是负担得起的。

function calculateSumRecursion(array) {
  return array.length === 0 ? "" : array[0] + calculateSumRecursion(array.slice(1));
}

There's a way easier way to do this:有一种更简单的方法可以做到这一点:

    function calculateSumRecursion(array) {
        var out = array[0];
        for (let i = 1; i < array.length; i++) {
            out = out + array[i];
        }
        return out;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM