Trying to use recursive function in JS, but code isn`t work:
let arr = [6, 5, 3, 1, 1, 1, 1]
function sum(ars, i) {
if (ars.length == i) {
return 0
}
return ars[i] + sum(ars[1])
}
console.log(sum(arr, 0))
// Output: 6
But the same code works in python:
arr = [2,5,3,1,1,1,1]
def sum(array):
if array==[]:
return 0
return array[0]+sum(array[1:])
print (sum(arr))
Can anyone explain what is the difference and what am I doing wrong in the JS code?
>Solution :
sum(ars[1])
ars[1] means "access the element at index 1". It does not get the tail of the array (ie, the sub-array from index 1 to n). Element 1 equals 5, so this is doing sum(5), which then gets messed up because the code expects an array, not a number.
To get the tail of an array you can use the slice method:
let arr = [6, 5, 3, 1, 1, 1, 1]
function sum(ars) {
if (ars.length == 0) {
return 0
}
return ars[0] + sum(ars.slice(1))
}
console.log(sum(arr))