在 CFScript 中使用 for-in 结构时的有趣行为
使用 for-in
时我注意到一些有趣的事情 构造于cfscript:看来 for(in)
循环中的 variable in struct
参数被设置为独立变量,并且没有对其父数组的引用钥匙。
如果运行以下代码,您将看到输出时数组没有更改。循环内的变量 local.i
被分配新值,但数组保持不变。
function arrayTest()
{
local.foo = ["bar-one","bar-two", "bar-three"];
for (local.i in local.foo)
{
local.i = "I am #local.i#";
// Dump local.i; its output will be 'I am bar-[one[two]] etc...'
}
// Dump local.i; its output will as above
// Dump the array; its keys remain unchanged: "bar-one, bar-two, -bar-three"
writeDump(local.foo);
}
那么这是为什么呢?我知道在 CF 中数组是通过引用传递的,但我在这里不传递数组。我只是在 for-in
结构中使用一个。有区别,不是吗?
将参数称为结构中的变量有点误导。 我将 local.i
视为 local.foo[ local.i ]
的快捷方式。听起来 var 确实是数组键,我们可以修改它。这里的解决方案是使用普通的 for()
循环。
I noticed something interesting when using for-in
constructs in cfscript: It appears that the variable in struct
argument in the for(in)
loop is set as an independent variable, and has no reference to its parent array key.
If you run the following code you will see the array doesn't change on output. The variable local.i
inside the loop is being assigned the new value, but the array remains unchanged.
function arrayTest()
{
local.foo = ["bar-one","bar-two", "bar-three"];
for (local.i in local.foo)
{
local.i = "I am #local.i#";
// Dump local.i; its output will be 'I am bar-[one[two]] etc...'
}
// Dump local.i; its output will as above
// Dump the array; its keys remain unchanged: "bar-one, bar-two, -bar-three"
writeDump(local.foo);
}
So why is this? I know arrays are passed by reference in CF, but I'm not passing an array here. I'm just using one in a for-in
construct. There is a difference, no?
It's a bit misleading to call the argument variable in structure.
I see local.i
as a shortcut to local.foo[ local.i ]
. It sounds like the var is indeed the array key and we can modify it. The solution here is to use a plain for()
loop, instead.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不希望底层数组发生变化,除非
i
是某种复杂的对象或通过引用传递的东西。例如,如果 foo然后修改
local.ia = "I am key #local.ia#";
将修改数组中的对象,并且这些更改将反映在您的转储中。更新:
最终这归结为指针或引用。在松散术语中,
local.i
只是指向数组中对象的指针。因此,重置local.i
只是将那个变量指向内存中的其他对象。对阵列没有影响。注意到哈希码值的变化了吗?I would not expect the underlying array to change unless
i
was a complex object of some sort or something passed by reference. For example if foo werethen modifying
local.i.a = "I am key #local.i.a#";
would modify the object within the array, and those changes would be reflected in your dump.Update:
Ultimately this comes down to pointers or references. In loose terms,
local.i
is just a pointer to objects within the array. So resettinglocal.i
just points that variable at some other object in memory. It has no impact on the array. Notice the change in hashcode value?