Powershell array assignment assigns variable, not value?

末鹿安然 提交于 2019-12-19 07:54:30

问题


I have an example of a program that creates an array, and then attempts to assign the value of that array multiple times into another array as a multidimensional array.

$a =@(0,0,0)
$b = @($a,$a,$a)
$b[1][2]=2
$b
'And $a is changed too:'
$a

The output is:

PS E:\Workarea> .\what.ps1
0
0
2
0
0
2
0
0
2
And $a is changed too:
0
0
2

So in this instance, the variable is actually pointing to the original variable. This is very unexpected behavior. It's rather neat that one can do this, although I never did use unions that much in my C programming. But I'd like a way to actually just do the assignment of the value, not of the variable.

$b = @($a.clone(),$a.clone(),$a.clone())

I guess would work, but something tells me that there may be something a little more elegant than that.

Thanks for the input.

This is PowerShell 2.0 under Windows 7 64-bit.


回答1:


To assign the values of $a to $b instead of the reference to $a, you can wrap the variable in $(). Anything in $() gets evaluated before using it in the command, so $($a) is equivalent to 0, 0, 0.

$a =@(0,0,0)
$b = @($($a),$($a),$($a))
$b[1][2]=2
$b
'$a is not changed.'
$a



回答2:


Be careful in PowerShell ',' is not the enumerator operator, but an array aoperator. The thing you present as multidimensional array is in fact an array of array, you'll find here under the definition of a multidimensional array :

$a= new-object ‘object[,]’ 3,3
$a[0,2]=3 
PS > for ($i=0;$i -lt 3;$i++)
>> {
>> for($j=0;$j -lt 3;$j++)
>> {
>> $a[$i,$j]=$i+$j
>> }
>> }

Everything work here as $b is an array of reference.



来源:https://stackoverflow.com/questions/8784487/powershell-array-assignment-assigns-variable-not-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!