首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么在嵌套循环中重新使用迭代器变量不会导致ColdFusion中的问题?

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

Stack Overflow用户
提问于 2013-10-09 09:08:04
回答 1查看 186关注 0票数 0

我一直在研究一些旧代码,我发现了几个嵌套循环的实例,在这些实例中,用于迭代对象的变量在内部循环中重新分配,但不会引起问题。例如,给定以下example.cfm

代码语言:javascript
复制
<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甚至没有作用域的情况下。然而,该函数将返回一个不可预测的结果。为什么?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-10-09 09:27:38

你没在桌子上检查密码。这是错误的,但它的工作,如预期。

代码语言:javascript
复制
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]

我认为你误解了这一行代码:

代码语言:javascript
复制
arrayAppend(filtered, inner);

你读到:

代码语言:javascript
复制
arrayAppend(filtered, inner[i]);

但它没有这么说。

讲得通?

票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19267567

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档