0

我一直在查看一些工作中的旧代码,并且发现了几个嵌套循环实例,其中用于迭代对象的变量在内部循环中重新分配,但不会引起问题。例如给出以下内容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 是甚至没有 scoped。但是,该函数将返回不可预测的结果。为什么?

4

1 回答 1

6

您没有正确地检查代码。这是错误的,但它按预期工作。

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]);

但它没有这么说。

说得通?

于 2013-10-09T09:27:38.340 回答