我一直在研究一些旧代码,我发现了几个嵌套循环的实例,在这些实例中,用于迭代对象的变量在内部循环中重新分配,但不会引起问题。例如,给定以下example.cfm
<cfscript>
// Get every second value in an array of arrays
function contrivedExampleFunction(required array data) {
var filtered = [];
for (i = 1; i lte arrayLen(arguments.data); i++) {
var inner = arguments.data[i];
for (i = 1; i lte arrayLen(inner); i++) {
if (i eq 2) {
arrayAppend(filtered, inner);
}
}
}
return filtered;
}
data = [
[1,2,3],
[4,5,6],
[7,8,9]
];
// Expected (working function): [2, 5, 8]
// Expected (short-circuiting): [2]
// Actual result: [1, 2, 3]
writeDump( contrivedExampleFunction(data) );
</cfscript>我希望内部i声明重新分配外部i并导致函数“短路”,特别是在i甚至没有作用域的情况下。然而,该函数将返回一个不可预测的结果。为什么?
发布于 2013-10-09 09:27:38
你没在桌子上检查密码。这是错误的,但它的工作,如预期。
The outer loop will loop i from 1-3
First iteration i=1
inner = data[1] => [1,2,3]
The inner loop will loop i from 1-3
First iteration i=1
nothing to do
Second iteration i=2
append inner to filtered => [1,2,3]
Third iteration i=3
nothing to do
end inner loop
i=3, which meets the exit condition of the outer loop
end of outer loop
filtered = [1,2,3]我认为你误解了这一行代码:
arrayAppend(filtered, inner);你读到:
arrayAppend(filtered, inner[i]);但它没有这么说。
讲得通?
https://stackoverflow.com/questions/19267567
复制相似问题