Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/375.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript之谜:函数中的变量_Javascript_Function - Fatal编程技术网

Javascript之谜:函数中的变量

Javascript之谜:函数中的变量,javascript,function,Javascript,Function,好吧,我很困惑,主要是因为我没有充分使用javascript。我知道这是一个数组指针问题(我必须在函数中复制数组…),但不确定如何修复它。我可以麻烦你解释一下为什么我的Javascript版本不工作而Python版本工作吗?它应该反转数组(我知道有一个内置的),但我的问题是:Javascript中的数组与Python中的数组如何区别对待 Javascript (does not work): function reverseit(x) { if (x.length == 0) { re

好吧,我很困惑,主要是因为我没有充分使用javascript。我知道这是一个数组指针问题(我必须在函数中复制数组…),但不确定如何修复它。我可以麻烦你解释一下为什么我的Javascript版本不工作而Python版本工作吗?它应该反转数组(我知道有一个内置的),但我的问题是:Javascript中的数组与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"     
应该是

  var found = x.pop();
  var found2 = reverseit(x);
在不本地化这些变量的情况下,您将它们声明为全局变量,并在每次调用
reverseit
时重写它们的值。顺便说一句,这些错误可以通过
“严格使用”来防止指令(),如果开发人员的浏览器支持它(我认为应该支持)

显然,代码在Python中工作,因为
found
found2
是本地的

但是看看JS生活中光明的一面:你可以这样写函数:

function reverseit(x) {
  return x.length 
         ? x.pop() + " " + reverseit(x) 
         : "";
};
console.log(reverseit(['the', 'big', 'dog']));

。。。根本不声明任何局部变量。

Yes;谢谢这解释了很多!这表明它与数组无关——我的错误在这里。函数中的内容应该是全局的,这似乎有点奇怪。。。但是有了正确的语法检查器,我想这可以被标记,这样像我这样的新手就不会被绊倒。谢谢你的快速回复。