wgw*_*wgw 3 javascript function
好吧,我很难过,主要是因为我没有足够使用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"
Run Code Online (Sandbox Code Playgroud)
==========================
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"
Run Code Online (Sandbox Code Playgroud)
它应该是...
var found = x.pop();
var found2 = reverseit(x);
Run Code Online (Sandbox Code Playgroud)
如果不对这些变量进行本地化,则将它们声明为全局变量 - 并在每次reverseit
调用时重写它们的值.顺便说一句,如果开发人员的浏览器支持这些错误,可以使用'use strict';
指令(MDN)来防止这些错误(在我看来应该是这样).
显然,代码在Python中工作,因为found
它found2
是本地的.
但是看看JS生活的光明面:你可以像这样编写这个函数:
function reverseit(x) {
return x.length
? x.pop() + " " + reverseit(x)
: "";
};
console.log(reverseit(['the', 'big', 'dog']));
Run Code Online (Sandbox Code Playgroud)
......根本没有声明任何局部变量.