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"
答案 0 :(得分:8)
应该是......
var found = x.pop();
var found2 = reverseit(x);
如果不对这些变量进行本地化,则会将它们声明为全局变量 - 并在每次调用reverseit
时重写它们的值。顺便说一句,如果开发人员的浏览器支持'use strict';
指令(MDN),则可以防止这些错误(在我看来应该是这样)。
显然,代码在Python中有效,因为found
和found2
是本地的。
但是看看JS生活的光明面:你可以像这样编写这个函数:
function reverseit(x) {
return x.length
? x.pop() + " " + reverseit(x)
: "";
};
console.log(reverseit(['the', 'big', 'dog']));
...根本没有声明任何局部变量。