如何检查数组是否包含特定值? [英] How do I check whether an array contains a particular value?
问题描述
我该怎么正确写呢?:
If number is different from Array[1] to Array[x-1] the begin......
其中number是整数,而array是整数数组从1到x
where number is an integer and array is an array of integers from 1 to x
推荐答案
我相信如果数字
MyArray 中找不到>。然后,您可以这样操作:
I believe you want to do something if number
is not found in the array MyArray
. Then you can do it like this:
NoMatch := true;
for i := Low(MyArray) to High(MyArray) do
if MyArray[i] = number then
begin
NoMatch := false;
break;
end;
if NoMatch then
DoYourThing;
您可以创建一个检查在数组中是否找到数字的函数。然后,您每次需要执行此类检查时都可以使用此功能。而且每次,代码都将更具可读性。例如,您可以这样操作:
You could create a function that checks if a number is found in an array. Then you can use this function every time you need to perform such a check. And each time, the code will be more readable. For example, you could do it like this:
function IsNumberInArray(const ANumber: integer;
const AArray: array of integer): boolean;
var
i: integer;
begin
for i := Low(AArray) to High(AArray) do
if ANumber = AArray[i] then
Exit(true);
result := false;
end;
...
if not IsNumberInArray(number, MyArray) then
DoYourThing;
如果使用旧版的Delphi,则必须替换 Exit(真)
通过开始结果:= true;打破;结束
。我想在较新版本的Delphi中,您还可以玩通用之类的东西。
If you use a old version of Delp you have to replace Exit(true)
by begin result := true; break; end
. In newer versions of Delp I suppose you could also play with stuff like generics.
这篇关于如何检查数组是否包含特定值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!