mercredi 6 janvier 2016

What's wrong with return here?

I'm working my way through eloquent javascript and for whatever reason return simply isn't working in the function nth. I honestly don't understand why it isn't working. I know I'm pretty close to getting the recursive version on nth working. This bug makes no sense to me. Here is all the relevant code:

function arrayToList(array) {
  list = null;
  for (i = 0; i < array.length; i++ ) {
    var x = array[array.length -(i + 1)];
    list = {value: x, rest: list};
  } return list;
}

function listToArray(list) {
  var array = [];
  var i = 0;
  for (var node = list; node; node = node.rest) {
    array[i] = node.value;
    i += 1;
  }
  return array;
}  


//return statements are broken here
function nth(list, number) {
 if (number == 0) {
   //console.log(list.value);
   return element;
   var element = list.value;
   } else if (number > 0) {
     list = list.rest;
     number--;
     //console.log(number);
     //console.log(list);
     nth(list, number);
   } else {
     return "Something went wrong";
     console.log(number);
   }
}

console.log(nth(arrayToList([10, 20, 30]), 1));

Can anyone explain why return statements aren't working in the in the nth function?

Aucun commentaire:

Enregistrer un commentaire