【发布时间】:2021-09-04 07:53:26
【问题描述】:
我在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,这是正确的
这里有什么问题?
【问题讨论】:
-
你到底想做什么?您的脚本没有如图所示运行。双管等
-
只检查数组
b的所有元素是否是数组a中任何数字的平方,其中数组a和b本身具有不同的元素。 -
简而言之:必须调用 PowerShell 函数、cmdlet、脚本和外部程序-
foo('arg1', 'arg2')。如果您使用,分隔参数,您将构造一个命令将其视为单个参数 的数组。为防止意外使用方法语法,请使用Set-StrictMode -Version 2或更高版本,但请注意其其他影响。请参阅this answer 了解更多信息。 -
如果传递的参数必须用空格分隔,那为什么还要执行并返回值呢?
-
您传递了一个锯齿状数组(一个二元素数组,其元素本身就是数组),并且由于错误使用方法语法,该数组作为一个整体绑定到您的
$a参数。$b参数没有绑定任何内容,但这不会导致错误,因为它是一个 可选 参数,因为所有 PowerShell 参数都是默认的。要使参数成为强制性参数,您需要用[Parameter(Mandatory)]装饰它 - 请参阅about_Functions_Advanced。