复合赋值运算符在子作用域中的行为如何?
How does the compound assignment operator behave in child scope?
下面两个函数会发生什么?我希望他们是一样的。
PS C:\> $i = 5
PS C:\> function Test1 { $i += 1; $i }
PS C:\> function Test2 { $i = $i + 1; $i }
PS C:\> Test1
1 # why?
PS C:\> Test2
6
PS C:\> $i
5 # will not change
我知道函数中的 $i 具有局部范围,因此不会在全局范围内更改,这是故意的。这个问题只是关于为什么以下2个赋值语句在这里表现不同,据我所知,它们应该是等价的。
$i = $i + 1
$i += 1
解释:
在 Test1
中,变量 $i
被 赋值 一个值(使用复合赋值运算符)。因为你不能从全局范围改变变量,所以创建了一个新的local变量(隐藏全局变量),它最初没有值(基本上是0),然后增加by 1.返回值时,使用局部变量
function Test1 {
# because it's an assignment, a new local variable
# is created (with initial value = 0)
$local:i += 1
$local:i
}
在Test2
中使用了global变量$i
的值(因为该变量在这个子范围内是可见的),添加1,结果 (6) 被分配给一个新的 local 变量。如Test1
,最后返回局部变量的值
function Test2 {
# a new local variable is created, but because the global
# variable is visible here, its value is used initially
$local:i = $global:i + 1
$local:i
}
在此处阅读有关范围的更多信息:about_scopes
至于...
I want the behavior of function Test2
($i = 5)
# Results
<#
5
#>
<#
要保存 time/code 单独调用变量,可以使用 PowerShell
变量压榨赋值给变量同时输出到屏幕
时间.
如果你总是要输出到屏幕,这会更直接。
这是一个选择,不会影响你正在做的事情
function Test1 { ($i += 1) }
function Test2 { ($i = $i + 1) }
Test1
Test2
# Results
<#
1
6
#>
($i = 5)
# Note the small refactor in the operator
function Test1 { ($i + 1) }
function Test2 { ($i = $i + 1) }
Test1
Test2
# Results
<#
6
6
#>
这仍然是一个范围问题,本地 vs 全局,但上面给出了两个调用中的匹配结果。
下面两个函数会发生什么?我希望他们是一样的。
PS C:\> $i = 5
PS C:\> function Test1 { $i += 1; $i }
PS C:\> function Test2 { $i = $i + 1; $i }
PS C:\> Test1
1 # why?
PS C:\> Test2
6
PS C:\> $i
5 # will not change
我知道函数中的 $i 具有局部范围,因此不会在全局范围内更改,这是故意的。这个问题只是关于为什么以下2个赋值语句在这里表现不同,据我所知,它们应该是等价的。
$i = $i + 1
$i += 1
解释:
在 Test1
中,变量 $i
被 赋值 一个值(使用复合赋值运算符)。因为你不能从全局范围改变变量,所以创建了一个新的local变量(隐藏全局变量),它最初没有值(基本上是0),然后增加by 1.返回值时,使用局部变量
function Test1 {
# because it's an assignment, a new local variable
# is created (with initial value = 0)
$local:i += 1
$local:i
}
在Test2
中使用了global变量$i
的值(因为该变量在这个子范围内是可见的),添加1,结果 (6) 被分配给一个新的 local 变量。如Test1
,最后返回局部变量的值
function Test2 {
# a new local variable is created, but because the global
# variable is visible here, its value is used initially
$local:i = $global:i + 1
$local:i
}
在此处阅读有关范围的更多信息:about_scopes
至于...
I want the behavior of function Test2
($i = 5)
# Results
<#
5
#>
<#
要保存 time/code 单独调用变量,可以使用 PowerShell 变量压榨赋值给变量同时输出到屏幕 时间.
如果你总是要输出到屏幕,这会更直接。
这是一个选择,不会影响你正在做的事情
function Test1 { ($i += 1) }
function Test2 { ($i = $i + 1) }
Test1
Test2
# Results
<#
1
6
#>
($i = 5)
# Note the small refactor in the operator
function Test1 { ($i + 1) }
function Test2 { ($i = $i + 1) }
Test1
Test2
# Results
<#
6
6
#>
这仍然是一个范围问题,本地 vs 全局,但上面给出了两个调用中的匹配结果。