我有兩個數組,需要將它們相加:
$Array1 = @(1,2,3,4,5)
$Array2 = @(2,3,4,5,1)
我需要遍歷每個元素並將它們加在一起(算術),以便我得到:
1+2
2+3
3+4
在一個數組中。我怎樣才能快速做到這一點?我正在使用 powershell 5.1。
您可以使用循環將每個數組中的數字相互連接,或者簡單地將它們相加。在這種情況下,我們將使用for
循環來遍歷數組中的每個項目:
$Array1 = @(1,2,3,4,5)
$Array2 = @(2,3,4,5,1)
for ($i = 0; $i -lt $Array1.Count; $i++)
{
Write-Host -Object "$($Array1[$i]) + $($Array2[$i])"
}
<#
OutPut:
1 + 2
2 + 3
3 + 4
4 + 5
5 + 1
#>
或者,如果您只是想添加它們:
$Array1 = @(1,2,3,4,5)
$Array2 = @(2,3,4,5,1)
for ($i = 0; $i -lt $Array1.Count; $i++)
{
$Array1[$i] + $Array2[$i]
}
<#
Output:
3
5
7
9
6
#>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句