为什么在嵌套循环中重用迭代器变量不会导致ColdFusion中出现问题?

i_l*_*ots 0 coldfusion cfc cfml

我一直在寻找一些旧的代码,我发现了几个嵌套循环实例,其中用于迭代对象的变量在内部循环中重新分配,但它不会导致问题.例如,给出以下内容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>
Run Code Online (Sandbox Code Playgroud)

我希望内部i声明重新分配外部i并使函数"短路",特别i 是因为甚至没有作用域.但是,该函数将返回不可预测的结果.为什么?

Ada*_*ron 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]
Run Code Online (Sandbox Code Playgroud)

我想你误读了这行代码:

arrayAppend(filtered, inner);
Run Code Online (Sandbox Code Playgroud)

你正在阅读它:

arrayAppend(filtered, inner[i]);
Run Code Online (Sandbox Code Playgroud)

但它并没有这么说.

合理?