OK, I’m stumped, mainly because I don’t use javascript enough. I know this is an array pointer problem (I must have to copy the array in the function…), but not sure how to fix it. Can I trouble you for an explanation why my Javascript version doesn’t work and the Python version does? It is supposed to reverse an array (I know there is a built-in), but my question is: How are arrays in Javascript treated differently than in Python?
Javascript (does not work):
function reverseit(x) {
if (x.length == 0) { return ""};
found = x.pop();
found2 = reverseit(x);
return found + " " + found2 ;
};
var out = reverseit(["the", "big", "dog"]);
// out == "the the the"
==========================
Python (works):
def reverseit(x):
if x == []:
return ""
found = x.pop()
found2 = reverseit(x)
return found + " " + found2
out = reverseit(["the", "big", "dog"]);
// out == "dog big the"
It should be…
Without localizing these variables you’ll declare them as global ones – and rewrite their values each time
reverseitis called. By the way, these errors can be prevented with'use strict';directive (MDN), if it’s supported by the developer’s browser (and it should be, in my opinion).Obviously the code works in Python because
foundandfound2are local there.But look at the bright side of JS life: you could just write that function like this:
… without declaring any local variables at all.