var funcs = [];
// let's create 3 functions
for (var i = 0; i < 3; i++) {
// and store them in funcs
funcs[i] = function() {
// each should log its value.
console.log("My value: " + i);
};
}
for (var j = 0; j < 3; j++) {
// and now let's run each one to see
funcs[j]();
}Run Code Online (Sandbox Code Playgroud)
它输出这个:
我的价值:3
我的价值:3
我的价值:3
而我希望它输出:
我的价值:0
我的价值:1
我的价值:2
使用事件侦听器导致运行函数的延迟时,会出现同样的问题:
var buttons = document.getElementsByTagName("button");
// let's create 3 …Run Code Online (Sandbox Code Playgroud)Python范围规则究竟是什么?
如果我有一些代码:
code1
class Foo:
code2
def spam.....
code3
for code4..:
code5
x()
Run Code Online (Sandbox Code Playgroud)
在哪里x找到?一些可能的选择包括以下列表:
在执行期间,当函数spam在其他地方传递时,也存在上下文.也许lambda函数的传递方式有点不同?
某处必须有简单的参考或算法.对于中级Python程序员来说,这是一个令人困惑的世界.
当我在调查Javascript代码中的词法闭包问题时,我在Python中遇到了这个问题:
flist = []
for i in xrange(3):
def func(x): return x * i
flist.append(func)
for f in flist:
print f(2)
Run Code Online (Sandbox Code Playgroud)
请注意,此示例谨慎避免lambda.它打印"4 4 4",这是令人惊讶的.我期待"0 2 4".
这个等效的Perl代码是正确的:
my @flist = ();
foreach my $i (0 .. 2)
{
push(@flist, sub {$i * $_[0]});
}
foreach my $f (@flist)
{
print $f->(2), "\n";
}
Run Code Online (Sandbox Code Playgroud)
打印"0 2 4".
你能解释一下这个区别吗?
更新:
这个问题是不是与i是全球性的.这显示相同的行为:
flist = []
def outer():
for i in xrange(3):
def inner(x): return x * i …Run Code Online (Sandbox Code Playgroud) 我正在尝试在循环内创建函数并将它们存储在字典中.问题是字典中的所有条目似乎最终都映射到最后创建的函数.代码如下:
functions = []
for i in range(3):
def f():
return i
# alternatively: f = lambda: i
functions.append(f)
Run Code Online (Sandbox Code Playgroud)
这输出:
print([f() for f in functions])
# expected output: [0, 1, 2]
# actual output: [2, 2, 2]
Run Code Online (Sandbox Code Playgroud)
知道为什么吗?