I'm trying to select Nth element from array using this function:
function nthArr(arr, index){
if (index === 0)
return arr[index];
else nthArr(arr.slice(1), --index);
}
nthArr([1,2,3,4,5,6],3)
I would await that it returns 4, but instead I get 'undefined'.
How should I return correct value?
rnevius
27.2k10 gold badges60 silver badges86 bronze badges
2 Answers 2
You are missing a return statement in the else branch.
if (index === 0)
return arr[index];
else {
return nthArr(arr.slice(1), --index); // Note the return
}
answered Sep 11, 2015 at 19:46
Mureinik
316k54 gold badges402 silver badges406 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
borism
exactly - my java habits :-)
You're missing a return statement...But why not just simplify the whole thing?
function nthArr(arr, index){
return arr[index];
}
var result = document.getElementById('result');
result.textContent = nthArr([1,2,3,4,5,6], 3);
<span id="result"></span>
answered Sep 11, 2015 at 19:53
rnevius
27.2k10 gold badges60 silver badges86 bronze badges
1 Comment
borism
yes this is simpler, but I needed it for traversing list object
lang-js
returnsomewhere afterelse?arr[index]work for all indices anyway?