我在Powershell
中有以下功能。它总是返回 False
而且数组的排序在函数中不起作用,而它在控制台中起作用。其功能是
# $a = [121, 144, 19, 161, 19, 144, 19, 11]
# $b = [121, 14641, 20736, 361, 25921, 361, 20736, 361]
function comp($a, $b) {
if( -Not ($a.length -Eq $b.length) || -Not $a || -Not $b) {
return $false
}
$a = $a | sort
$b = $b | sort
# Adding echo statements here to check if $a and $b are sorted tells that both are NOT sorted despite assigning them to the same variable
# Assigning the sorted arrays to other variables such as $x and $y again doesn't solve the problem. $x and $y also have the unsorted values
for($i=0;$i -lt $a.length;$i++) {
if( -Not ($b[$i] -Eq $a[$i]*$a[$i])) {
return $false
}
}
return $true
}
注意:顶部的$a和$b是在没有[
的情况下初始化的和]
提供它只是为了强调它们是数组。
上面的函数返回 False
而它必须是True
。然后我尝试了这个
function comp($a, $b) {
if( -Not ($a.length -Eq $b.length) || -Not $a || -Not $b) {
return $false
}
for($i=0;$i -lt $a.length;$i++) {
$flag = $false
for($j=0;$j -lt $b.length; $j++) {
if($b[$j] -Eq $a[$i]*$a[$i]) {
$flag = $true
# Never gets into this i.e. never executed
break;
}
}
if( -Not $flag) {
return $flag
}
}
return $true
}
它没有返回False
。因此,输出是 True
这是正确的
这里出了什么问题?
最佳答案
您错误地将参数传递给 comp
。
PowerShell 的命令调用语法要求您传递由空格分隔的参数,而不是逗号分隔的列表。
更改:
comp($a, $b)
至:
comp $a $b
# or
comp -a $a -b $b
请参阅about_Command_Syntax
help topic有关如何在 PowerShell 中调用命令的更多信息
关于powershell - 排序在 Powershell 函数中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68054431/