简体   繁体   中英

PowerShell - foreach() doesn't change element value

Say you have the array:

$arr = @(1,2,3,4,5,6,7,8,9)
foreach($number in $arr) { $number ++ }

I would expect the output to be:

$arr = @(2,3,4,5,6,7,8,9,10)

Why is this not true?

What you think you're doing is equivalent to this:

for ($i = 0; $i -lt $arr.Count; $i++) {
    $arr[$i]++;
}

What you're actually doing is equivalent to this:

for ($i = 0; $i -lt $arr.Count; $i++) {
    $number = $arr[$i];
    $number++;
}

What you really want to do is this:

$arr = $arr | ForEach-Object { $_ + 1; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM