foreach - PowerShell - Change items in an array - Stack Overflow

Correct me if I'm wrong, but shouldn't the below change each element in the array $List to &#

Correct me if I'm wrong, but shouldn't the below change each element in the array $List to 'ZZZ'?

> $List = @('a','b')
> ForEach($i In $List) { $i = 'ZZZ' }
> $List
a
b

Correct me if I'm wrong, but shouldn't the below change each element in the array $List to 'ZZZ'?

> $List = @('a','b')
> ForEach($i In $List) { $i = 'ZZZ' }
> $List
a
b
Share Improve this question edited Mar 26 at 20:07 Santiago Squarzon 61.6k5 gold badges24 silver badges54 bronze badges asked Mar 26 at 18:55 Ryan.JamesRyan.James 575 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 2

It would if you were dealing with mutable reference types, e.g. an array of hash tables:

$List = @{ Value = 'a' }, @{ Value = 'b' }
foreach ($i in $List) { $i.Value = 'ZZZ' }
$List

The loop modifies the original hash tables in $List because $i is a reference to each hash table, and hash tables are mutable reference types.

But for value types and strings in this case, which are reference types but are immutable, the assignment of $i doesn't change the string itself, just re-assigns the variable reference to a new string.

If you used a for loop instead of a foreach for example, and since arrays are also reference types, you could alter their elements, but again, this doesn't mean you're altering the strings themselves, just assigning a new reference to each array element.

$List = 'a', 'b'
for($i = 0; $i -lt $List.Length; $i++) { $List[$i] = 'ZZZ' }
$List

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744131353a4559857.html

相关推荐

  • foreach - PowerShell - Change items in an array - Stack Overflow

    Correct me if I'm wrong, but shouldn't the below change each element in the array $List to &#

    8天前
    10

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信