Attention: Here be dragons
This is the latest
(unstable) version of this documentation, which may document features
not available in or compatible with released stable versions of Godot.
Checking the stable version of the documentation...
Array
一种内置数据结构,包含一系列元素。
描述
An array data structure that can contain a sequence of elements of any Variant type. Elements are accessed by a numerical index starting at 0
. Negative indices are used to count from the back (-1
is the last element, -2
is the second to last, etc.).
var array = ["First", 2, 3, "Last"]
print(array[0]) # Prints "First"
print(array[2]) # Prints 3
print(array[-1]) # Prints "Last"
array[1] = "Second"
print(array[1]) # Prints "Second"
print(array[-3]) # Prints "Second"
Godot.Collections.Array array = ["First", 2, 3, "Last"];
GD.Print(array[0]); // Prints "First"
GD.Print(array[2]); // Prints 3
GD.Print(array[^1]); // Prints "Last"
array[1] = "Second";
GD.Print(array[1]); // Prints "Second"
GD.Print(array[^3]); // Prints "Second"
Note: Arrays are always passed by reference. To get a copy of an array that can be modified independently of the original array, use duplicate.
Note: Erasing elements while iterating over arrays is not supported and will result in unpredictable behavior.
Differences between packed arrays, typed arrays, and untyped arrays: Packed arrays are generally faster to iterate on and modify compared to a typed array of the same type (e.g. PackedInt64Array versus Array[int]
). Also, packed arrays consume less memory. As a downside, packed arrays are less flexible as they don't offer as many convenience methods such as map. Typed arrays are in turn faster to iterate on and modify than untyped arrays.
备注
通过 C# 使用该 API 时会有显著不同,详见 C# API 与 GDScript 的差异。
构造函数
Array() |
|
Array(base: Array, type: int, class_name: StringName, script: Variant) |
|
Array(from: PackedByteArray) |
|
Array(from: PackedColorArray) |
|
Array(from: PackedFloat32Array) |
|
Array(from: PackedFloat64Array) |
|
Array(from: PackedInt32Array) |
|
Array(from: PackedInt64Array) |
|
Array(from: PackedStringArray) |
|
Array(from: PackedVector2Array) |
|
Array(from: PackedVector3Array) |
|
Array(from: PackedVector4Array) |
方法
void |
|
void |
append_array(array: Array) |
void |
|
back() const |
|
bsearch_custom(value: Variant, func: Callable, before: bool = true) const |
|
void |
clear() |
void |
|
void |
|
find_custom(method: Callable, from: int = 0) const |
|
front() const |
|
get_typed_builtin() const |
|
get_typed_class_name() const |
|
get_typed_script() const |
|
hash() const |
|
is_empty() const |
|
is_read_only() const |
|
is_same_typed(array: Array) const |
|
is_typed() const |
|
void |
|
max() const |
|
min() const |
|
pick_random() const |
|
pop_back() |
|
void |
|
void |
push_front(value: Variant) |
void |
|
void |
reverse() |
rfind_custom(method: Callable, from: int = -1) const |
|
void |
|
void |
shuffle() |
size() const |
|
slice(begin: int, end: int = 2147483647, step: int = 1, deep: bool = false) const |
|
void |
sort() |
void |
sort_custom(func: Callable) |
运算符
operator !=(right: Array) |
|
operator +(right: Array) |
|
operator <(right: Array) |
|
operator <=(right: Array) |
|
operator ==(right: Array) |
|
operator >(right: Array) |
|
operator >=(right: Array) |
|
operator [](index: int) |
构造函数说明
构造空的 Array。
Array Array(base: Array, type: int, class_name: StringName, script: Variant)
根据 base
数组创建类型化的数组。类型化的数组只能包含给定类型的元素,或者从给定类继承的元素,构造函数的参数如下所述:
type
是内置 Variant 类型,是一个 Variant.Type 常量。class_name
是内置类名(见 Object.get_class)。script
是关联的脚本。它必须是 Script 实例或null
。
如果 type
不是 @GlobalScope.TYPE_OBJECT,则 class_name
必须为空的 StringName,且 script
必须为 null
。
class_name Sword
extends Node
class Stats:
pass
func _ready():
var a = Array([], TYPE_INT, "", null) # Array[int]
var b = Array([], TYPE_OBJECT, "Node", null) # Array[Node]
var c = Array([], TYPE_OBJECT, "Node", Sword) # Array[Sword]
var d = Array([], TYPE_OBJECT, "RefCounted", Stats) # Array[Stats]
base
数组的元素在必要时进行转换。如果无法转换或 base
已被类型化,则该构造函数失败并返回一个空的 Array。
在 GDScript 中,这个构造函数通常不是必需的,因为可以通过静态类型创建类型化的数组:
var numbers: Array[float] = []
var children: Array[Node] = [$Node, $Sprite2D, $RigidBody3D]
var integers: Array[int] = [0.2, 4.5, -2.0]
print(integers) # 输出 [0, 4, -2]
返回与 from
相同的数组。如果你需要一个数组的副本,请使用 duplicate。
Array Array(from: PackedByteArray)
从 PackedByteArray 构造一个数组。
Array Array(from: PackedColorArray)
从 PackedColorArray 构造一个数组。
Array Array(from: PackedFloat32Array)
从 PackedFloat32Array 构造一个数组。
Array Array(from: PackedFloat64Array)
从 PackedFloat64Array 构造一个数组。
Array Array(from: PackedInt32Array)
从 PackedInt32Array 构造一个数组。
Array Array(from: PackedInt64Array)
从 PackedInt64Array 构造一个数组。
Array Array(from: PackedStringArray)
从 PackedStringArray 构造一个数组。
Array Array(from: PackedVector2Array)
从 PackedVector2Array 构造一个数组。
Array Array(from: PackedVector3Array)
从 PackedVector3Array 构造一个数组。
Array Array(from: PackedVector4Array)
从 PackedVector4Array 构造一个数组。
方法说明
bool all(method: Callable) const 🔗
Calls the given Callable on each element in the array and returns true
if the Callable returns true
for all elements in the array. If the Callable returns false
for one array element or more, this method returns false
.
The method
should take one Variant parameter (the current array element) and return a bool.
func greater_than_5(number):
return number > 5
func _ready():
print([6, 10, 6].all(greater_than_5)) # Prints true (3/3 elements evaluate to true).
print([4, 10, 4].all(greater_than_5)) # Prints false (1/3 elements evaluate to true).
print([4, 4, 4].all(greater_than_5)) # Prints false (0/3 elements evaluate to true).
print([].all(greater_than_5)) # Prints true (0/0 elements evaluate to true).
# Same as the first line above, but using a lambda function.
print([6, 10, 6].all(func(element): return element > 5)) # Prints true
private static bool GreaterThan5(int number)
{
return number > 5;
}
public override void _Ready()
{
// Prints True (3/3 elements evaluate to true).
GD.Print(new Godot.Collections.Array>int< { 6, 10, 6 }.All(GreaterThan5));
// Prints False (1/3 elements evaluate to true).
GD.Print(new Godot.Collections.Array>int< { 4, 10, 4 }.All(GreaterThan5));
// Prints False (0/3 elements evaluate to true).
GD.Print(new Godot.Collections.Array>int< { 4, 4, 4 }.All(GreaterThan5));
// Prints True (0/0 elements evaluate to true).
GD.Print(new Godot.Collections.Array>int< { }.All(GreaterThan5));
// Same as the first line above, but using a lambda function.
GD.Print(new Godot.Collections.Array>int< { 6, 10, 6 }.All(element => element > 5)); // Prints True
}
See also any, filter, map and reduce.
Note: Unlike relying on the size of an array returned by filter, this method will return as early as possible to improve performance (especially with large arrays).
Note: For an empty array, this method always returns true
.
bool any(method: Callable) const 🔗
对数组中的每个元素调用给定的 Callable,如果 Callable 为数组中的* 一个或多个*元素返回 true
,则返回 true
。如果 Callable 为数组中的所有元素返回 false
,则该方法返回 false
。
该 method
应接受一个 Variant 参数(当前数组元素)并返回一个 bool。
func greater_than_5(number):
return number > 5
func _ready():
print([6, 10, 6].any(greater_than_5)) # 输出 true (3 个元素被评估为真)。
print([4, 10, 4].any(greater_than_5)) #输出 true (1 个元素被评估为真)。
print([4, 4, 4].any(greater_than_5)) # 输出 false (0 个元素被评估为真)。
print([].any(greater_than_5)) # 输出 false (0 个元素被评估为真)。
# 与上面的第一行相同,但使用 lambda 函数。
print([6, 10, 6].any(func(number): return number > 5)) # 输出 true
注意:与依赖 filter 返回的数组大小不同,此方法会尽可能早地返回以提高性能(尤其是对于大型数组)。
注意:对于一个空数组,这个方法总是返回 false
。
将 value
追加到数组末尾(push_back 的别名)。
void append_array(array: Array) 🔗
在该数组的末尾追加其他 array
。
var numbers = [1, 2, 3]
var extra = [4, 5, 6]
numbers.append_array(extra)
print(numbers) # 输出 [1, 2, 3, 4, 5, 6]
将另一个 array
的元素赋值到该数组中。调整数组大小以匹配 array
。如果数组是有类型的,则执行类型转换。
返回数组的最后一个元素。如果数组为空,则失败并返回 null
。另请参阅 front。
注意:与 []
运算符(array[-1]
)不同,错误生成时不会停止项目执行。
int bsearch(value: Variant, before: bool = true) const 🔗
返回已排序数组中 value
的索引。如果找不到,则返回应被插入 value
的位置以保持数组被排序。使用的算法是二分查找算法。
如果 before
为 true
(默认情况下),则返回的索引位于数组中所有等于 value
的已有元素之前。
var numbers = [2, 4, 8, 10]
var idx = numbers.bsearch(7)
numbers.insert(idx, 7)
print(numbers) # 输出 [2, 4, 7, 8, 10]
var fruits = ["Apple", "Lemon", "Lemon", "Orange"]
print(fruits.bsearch("Lemon", true)) # 输出 1,位于第一个 "Lemon"。
print(fruits.bsearch("Lemon", false)) # 输出 3,位于 "Orange"。
注意:对未排序的数组调用 bsearch 将导致意外行为。调用该方法之前,请使用 sort。
int bsearch_custom(value: Variant, func: Callable, before: bool = true) const 🔗
返回已排序数组中 value
的索引。如果找不到,则返回 value
应插入的位置,以保持数组已排序(使用 func
进行比较)。使用的算法是二分查找算法。
与 sort_custom 类似,func
会根据需要多次调用,接收一个数组元素和 value
作为参数。如果数组元素应该在 value
后面,则函数应该返回 true
,否则应该返回 false
。
如果 before
为 true
(默认情况下),则返回的索引位于数组中所有等于 value
的已有元素之前。
func sort_by_amount(a, b):
if a[1] < b[1]:
return true
return false
func _ready():
var my_items = [["Tomato", 2], ["Kiwi", 5], ["Rice", 9]]
var apple = ["Apple", 5]
# "Apple" 被插入在 "Kiwi" 之前。
my_items.insert(my_items.bsearch_custom(apple, sort_by_amount, true), apple)
var banana = ["Banana", 5]
# "Banana" 被插入在 "Kiwi" 之后。
my_items.insert(my_items.bsearch_custom(banana, sort_by_amount, false), banana)
# 输出 [["Tomato", 2], ["Apple", 5], ["Kiwi", 5], ["Banana", 5], ["Rice", 9]]
print(my_items)
注意:在未排序的数组上调用 bsearch_custom 将导致意外行为。在调用该方法之前,请将 sort_custom 与 func
结合使用。
void clear() 🔗
从该数组中移除所有元素。相当于调用 resize 时指定大小为 0
。
int count(value: Variant) const 🔗
Returns the number of times an element is in the array.
To count how many elements in an array satisfy a condition, see reduce.
Array duplicate(deep: bool = false) const 🔗
返回数组的新副本。
默认情况下返回的是浅拷贝:嵌套的 Array 和 Dictionary 元素与原数组共享。对这些元素的修改会影响另一个数组。
如果 deep
为 true
则会返回深拷贝:嵌套的数组和字典也会进行(递归的)复制。
查找并从数组中移除 value
的第一个匹配值。如果数组中不存在 value
,则什么也不会发生。要通过索引移除元素,请改用 remove_at。
注意:该方法将移除的 value
后每个元素的索引移回一位,这可能会产生明显的性能成本,尤其是在较大的数组上。
注意:在迭代数组时移除元素不受支持,并且将导致不可预测的行为。
Assigns the given value
to all elements in the array.
This method can often be combined with resize to create an array with a given size and initialized elements:
var array = []
array.resize(5)
array.fill(2)
print(array) # Prints [2, 2, 2, 2, 2]
Godot.Collections.Array array = [];
array.Resize(5);
array.Fill(2);
GD.Print(array); // Prints [2, 2, 2, 2, 2]
Note: If value
is a Variant passed by reference (Object-derived, Array, Dictionary, etc.), the array will be filled with references to the same value
, which are not duplicates.
Array filter(method: Callable) const 🔗
在数组中的每个元素上调用给定的 Callable,并返回一个新的、经过过滤的 Array。
该 method
接收一个数组元素作为参数,并且应返回 true
以将该元素添加到过滤后的数组中,或返回 false
以将其排除。
func is_even(number):
return number % 2 == 0
func _ready():
print([1, 4, 5, 8].filter(is_even)) # 输出 [4, 8]
# 与上面相同,但使用 lambda 函数。
print([1, 4, 5, 8].filter(func(number): return number % 2 == 0))
int find(what: Variant, from: int = 0) const 🔗
返回 what
在该数组中第一次出现时的索引,不存在时返回 -1
。搜索的起点可以使用 from
指定,终点为数组末尾。
注意:如果你只想知道数组中是否包含 what
,请使用 has(C# 则为 Contains
)。在 GDScript 中,你还可以使用 in
运算符。
注意:出于性能方面的考虑,搜索时会使用到 what
的 Variant.Type。例如该方法不会认为 7
(int)和 7.0
(float)相等。
int find_custom(method: Callable, from: int = 0) const 🔗
Returns the index of the first element in the array that causes method
to return true
, or -1
if there are none. The search's start can be specified with from
, continuing to the end of the array.
method
is a callable that takes an element of the array, and returns a bool.
Note: If you just want to know whether the array contains anything that satisfies method
, use any.
func is_even(number):
return number % 2 == 0
func _ready():
print([1, 3, 4, 7].find_custom(is_even.bind())) # Prints 2
返回数组的第一个元素。如果数组为空,则失败并返回 null
。另请参阅 back。
注意:与 []
运算符(array[0]
)不同,错误产生时不会停止项目执行。
Variant get(index: int) const 🔗
Returns the element at the given index
in the array. This is the same as using the []
operator (array[index]
).
int get_typed_builtin() const 🔗
将类型化数组的内置 Variant 类型作为 Variant.Type 常量返回。如果该数组不是类型化的,则返回 @GlobalScope.TYPE_NIL。另请参阅 is_typed。
StringName get_typed_class_name() const 🔗
如果内置 Variant 类型为 @GlobalScope.TYPE_OBJECT,则返回类型数组的内置类名。否则,返回一个空的 StringName。另请参阅 is_typed 和 Object.get_class。
Variant get_typed_script() const 🔗
返回与该类型数组关联的 Script 实例,如果不存在则返回 null
。另请参阅 is_typed。
bool has(value: Variant) const 🔗
Returns true
if the array contains the given value
.
print(["inside", 7].has("inside")) # Prints true
print(["inside", 7].has("outside")) # Prints false
print(["inside", 7].has(7)) # Prints true
print(["inside", 7].has("7")) # Prints false
Godot.Collections.Array arr = ["inside", 7];
// By C# convention, this method is renamed to `Contains`.
GD.Print(arr.Contains("inside")); // Prints True
GD.Print(arr.Contains("outside")); // Prints False
GD.Print(arr.Contains(7)); // Prints True
GD.Print(arr.Contains("7")); // Prints False
In GDScript, this is equivalent to the in
operator:
if 4 in [2, 4, 6, 8]:
print("4 is here!") # Will be printed.
Note: For performance reasons, the search is affected by the value
's Variant.Type. For example, 7
(int) and 7.0
(float) are not considered equal for this method.
返回代表该数组及其内容的散列 32 位整数值。
注意:由于哈希碰撞的缘故,哈希相同的数组不保证相同。而相对的是,哈希不同的数组保证不同。
int insert(position: int, value: Variant) 🔗
在数组中给定索引(position
)处插入新元素(value
)。position
应介于 0
和数组的 size 之间。
如果成功,则返回 @GlobalScope.OK;如果该方法失败,则返回其他 Error 常量之一。
注意:position
之后的每个元素的索引都需要向前移动,这可能会产生明显的性能成本,尤其是在较大的数组上。
如果数组为空([]
),则返回 true
。另请参阅 size。
如果该数组是只读的,则返回 true
。请参阅 make_read_only。
在 GDScript 中,如果数组是使用 const
关键字声明的,则该数组自动为只读。
bool is_same_typed(array: Array) const 🔗
如果该数组的类型与给定的 array
相同,则返回 true
。另请参阅 is_typed。
如果数组是类型化的,则返回 true
。类型化数组只能包含由类型化数组构造函数定义的特定类型的元素。类型化数组的方法仍应返回通用 Variant。
在 GDScript 中,可以使用静态类型定义类型化数组:
var numbers: Array[float] = [0.2, 4.2, -2.0]
print(numbers.is_typed()) # 输出 true
void make_read_only() 🔗
使数组只读。数组的元素无法使用其他值覆盖,顺序也无法改变。不适用于字典等嵌套的元素。
在 GDScript 中,使用 const
关键字声明的数组会自动变为只读。
Array map(method: Callable) const 🔗
为数组中的每个元素调用给定的 Callable 并返回一个新数组,其中填充了该 method
返回的值。
method
应该采用一个 Variant 参数(当前数组元素)并且可以返回任意 Variant。
func double(number):
return number * 2
func _ready():
print([1, 2, 3].map(double)) # 输出 [2, 4, 6]
# 与上面相同,但使用 lambda 函数。
print([1, 2, 3].map(func(element): return element * 2))
如果所有元素都可以比较,则返回数组中包含元素的最大值。否则,返回 null
。另请参阅 min。
要使用自定义比较器查找最大值,可以使用 reduce。
如果所有元素都可以比较,则返回数组中包含元素的最小值。否则,返回 null
。另请参阅 max。
Returns a random element from the array. Generates an error and returns null
if the array is empty.
# May print 1, 2, 3.25, or "Hi".
print([1, 2, 3.25, "Hi"].pick_random())
Godot.Collections.Array array = [1, 2, 3.25f, "Hi"];
GD.Print(array.PickRandom()); // May print 1, 2, 3.25, or "Hi".
Note: Like many similar functions in the engine (such as @GlobalScope.randi or shuffle), this method uses a common, global random seed. To get a predictable outcome from this method, see @GlobalScope.seed.
Variant pop_at(position: int) 🔗
移除并返回数组中位于 position
索引处的元素。如果 position
为负数,则认为是相对于该数组末尾的值。如果数组为空,则返回 null
;如果 position
超出范围,还会生成错误消息。
注意:该方法将 position
之后每个元素的索引向后移动,这可能会产生明显的性能成本,尤其是在较大的数组上。
移除并返回数组中的末尾元素。如果数组为空,则返回 null
,而不会生成错误。另见 pop_front。
移除并返回数组的第一个元素。如果数组为空,则返回 null
,而不会生成错误。另请参阅 pop_back。
注意:该方法将每个其他元素的索引向后移动,这可能会产生明显的性能成本,尤其是在较大的数组上。
void push_back(value: Variant) 🔗
在数组的末端追加一个元素。另请参阅 push_front。
void push_front(value: Variant) 🔗
在数组的开头添加一个元素。另请参阅 push_back。
注意:该方法将每个其他元素的索引向前移动,这可能会产生明显的性能成本,尤其是在较大的数组上。
Variant reduce(method: Callable, accum: Variant = null) const 🔗
Calls the given Callable for each element in array, accumulates the result in accum
, then returns it.
The method
takes two arguments: the current value of accum
and the current array element. If accum
is null
(as by default), the iteration will start from the second element, with the first one used as initial value of accum
.
func sum(accum, number):
return accum + number
func _ready():
print([1, 2, 3].reduce(sum, 0)) # Prints 6
print([1, 2, 3].reduce(sum, 10)) # Prints 16
# Same as above, but using a lambda function.
print([1, 2, 3].reduce(func(accum, number): return accum + number, 10))
If max is not desirable, this method may also be used to implement a custom comparator:
func _ready():
var arr = [Vector2i(5, 0), Vector2i(3, 4), Vector2i(1, 2)]
var longest_vec = arr.reduce(func(max, vec): return vec if is_length_greater(vec, max) else max)
print(longest_vec) # Prints (3, 4)
func is_length_greater(a, b):
return a.length() > b.length()
This method can also be used to count how many elements in an array satisfy a certain condition, similar to count:
func is_even(number):
return number % 2 == 0
func _ready():
var arr = [1, 2, 3, 4, 5]
# If the current element is even, increment count, otherwise leave count the same.
var even_count = arr.reduce(func(count, next): return count + 1 if is_even(next) else count, 0)
print(even_count) # Prints 2
See also map, filter, any, and all.
void remove_at(position: int) 🔗
从数组中移除指定索引(position
)处的元素。如果索引超出范围,则该方法失败。
如果需要返回被移除的元素,请使用 pop_at。要按值移除元素,请改用 erase。
注意:该方法将 position
之后每个元素的索引向后移,这可能会产生明显的性能成本,尤其是在较大的数组上。
注意:position
不能为负数。要移除相对于数组末尾的元素,请使用 arr.remove_at(arr.size() - (i + 1))
。要从数组中移除最后一个元素,请使用 arr.resize(arr.size() - 1)
。
将数组的元素数设置为 size
。如果 size
小于数组的当前大小,则移除末尾的元素。如果 size
大于数组的当前大小,则添加新的默认元素(通常为 null
),具体取决于数组的类型。
如果成功,则返回 @GlobalScope.OK;如果该方法失败,则返回其他 Error 常量之一。
注意:调用该方法一次并分配新值,要比为每个新元素调用 append 更快。
void reverse() 🔗
反转数组中所有元素的顺序。
int rfind(what: Variant, from: int = -1) const 🔗
返回该数组中 what
最后一次出现时的索引,不存在时则为 -1
。搜索的起点可以用 from
指定,终点为该数组的开头。该方法与 find 相对。
int rfind_custom(method: Callable, from: int = -1) const 🔗
Returns the index of the last element of the array that causes method
to return true
, or -1
if there are none. The search's start can be specified with from
, continuing to the beginning of the array. This method is the reverse of find_custom.
void set(index: int, value: Variant) 🔗
Sets the value of the element at the given index
to the given value
. This will not change the size of the array, it only changes the value at an index already in the array. This is the same as using the []
operator (array[index] = value
).
void shuffle() 🔗
随机打乱数组中所有元素的顺序。
注意:与引擎中很多类似的函数一样(例如 @GlobalScope.randi 和 pick_random),该方法使用的是通用的全局随机数种子。如何获取可预知的结果见 @GlobalScope.seed。
返回该数组中元素的数量。空数组([]
)始终返回 0
。另请参阅 is_empty。
Array slice(begin: int, end: int = 2147483647, step: int = 1, deep: bool = false) const 🔗
返回一个新的 Array,其中包含该数组的元素,从索引 begin
(含)到 end
(不含),每个 step
个元素。
如果 begin
或 end
为负数,则它们的值相对于数组的末尾。
如果 step
为负数,则该方法反向遍历数组,返回按反向顺序排列的切片数组。要使其起作用,begin
必须大于 end
。
如果 deep
为 true
,则切片数组中所有嵌套的 Array 和 Dictionary 元素都将从原始元素中递归复制。另请参阅 duplicate)。
var letters = ["A", "B", "C", "D", "E", "F"]
print(letters.slice(0, 2)) # 输出 ["A", "B"]
print(letters.slice(2, -2)) # 输出 ["C", "D"]
print(letters.slice(-2, 6)) # 输出 ["E", "F"]
print(letters.slice(0, 6, 2)) # 输出 ["A", "C", "E"]
print(letters.slice(4, 1, -1)) # 输出 ["E", "D", "C"]
void sort() 🔗
Sorts the array in ascending order. The final order is dependent on the "less than" (<
) comparison between elements.
var numbers = [10, 5, 2.5, 8]
numbers.sort()
print(numbers) # Prints [2.5, 5, 8, 10]
Godot.Collections.Array numbers = [10, 5, 2.5, 8];
numbers.Sort();
GD.Print(numbers); // Prints [2.5, 5, 8, 10]
Note: The sorting algorithm used is not stable. This means that equivalent elements (such as 2
and 2.0
) may have their order changed when calling sort.
void sort_custom(func: Callable) 🔗
使用自定义的 Callable 对数组进行排序。
func
可根据需要多次调用,接收两个数组元素作为参数。如果第一个元素应移到第二个元素的前面,则该函数应返回 true
,否则应返回 false
。
func sort_ascending(a, b):
if a[1] < b[1]:
return true
return false
func _ready():
var my_items = [["Tomato", 5], ["Apple", 9], ["Rice", 4]]
my_items.sort_custom(sort_ascending)
print(my_items) # 输出 [["Rice", 4], ["Tomato", 5], ["Apple", 9]]
# 使用 lambda 函数按降序排序。
my_items.sort_custom(func(a, b): return a[0] > b[0])
print(my_items) # 输出 [["Apple", 9], ["Tomato", 5], ["Rice", 4]]
可能还需要使用该方法按自然顺序对字符串进行排序,使用 String.naturalnocasecmp_to,如下例所示:
var files = ["newfile1", "newfile2", "newfile10", "newfile11"]
files.sort_custom(func(a, b): return a.naturalnocasecmp_to(b) < 0)
print(files) # 输出 ["newfile1", "newfile2", "newfile10", "newfile11"]
注意:在 C# 中,不支持该方法。
注意:使用的排序算法并不是稳定的。这意味着在调用该方法时,被视为相等的值的顺序可能会发生变化。
注意:不应随机化 func
的返回值,因为堆排序算法需要一致的结果。随机化返回值将导致意外行为。
运算符说明
bool operator !=(right: Array) 🔗
如果该数组的大小或其元素与 right
不同,则返回 true
。
Array operator +(right: Array) 🔗
Appends the right
array to the left operand, creating a new Array. This is also known as an array concatenation.
var array1 = ["One", 2]
var array2 = [3, "Four"]
print(array1 + array2) # Prints ["One", 2, 3, "Four"]
// Note that concatenation is not possible with C#'s native Array type.
Godot.Collections.Array array1 = ["One", 2];
Godot.Collections.Array array2 = [3, "Four"];
GD.Print(array1 + array2); // Prints ["One", 2, 3, "Four"]
Note: For existing arrays, append_array is much more efficient than concatenation and assignment with the +=
operator.
bool operator <(right: Array) 🔗
按顺序比较两个数组的元素,从索引 0
开始,到两个数组共同的最后一个索引结束。对于每对元素,如果该数组的元素小于 right
的元素,则返回 true
;如果该元素大于 right
的元素,则返回 false
。否则,继续下一对。
当所有搜索到的元素都相等时,如果该数组的大小小于 right
的大小,则返回 true
,否则返回 false
。
bool operator <=(right: Array) 🔗
按顺序比较两个数组的元素,从索引 0
开始,到两个数组共同的最后一个索引结束。对于每对元素,如果该数组的元素小于 right
的元素,则返回 true
;如果该元素较大则返回 false
。否则,继续下一对。
当所有搜索到的元素都相等时,如果该数组的大小小于或等于 right
的大小,则返回 true
,否则返回 false
。
bool operator ==(right: Array) 🔗
将左操作数 Array 与 right
Array 进行比较。如果数组的大小和内容相等,则返回 true
,否则返回 false
。
bool operator >(right: Array) 🔗
按顺序比较两个数组的元素,从索引 0
开始,到两个数组共同的最后一个索引结束。对于每对元素,如果该数组的元素大于 right
的元素,则返回 true
;如果该元素较小则返回 false
。否则,继续下一对。
当所有搜索到的元素都相等时,如果该数组的大小大于 right
的大小,则返回 true
,否则返回 false
。
bool operator >=(right: Array) 🔗
按顺序比较两个数组的元素,从索引 0
开始,到两个数组共同的最后一个索引结束。对于每对元素,如果该数组的元素大于 right
的元素,则返回 true
,如果该元素较小则返回 false
。否则,继续下一对。
当所有搜索到的元素都相等时,如果该数组的大小大于或等于 right
的大小,则返回 true
,否则返回 false
。
Variant operator [](index: int) 🔗
返回指定 index
处的 Variant 元素。数组从索引 0 开始。如果 index
大于或等于 0
,则从数组开头开始获取元素。如果 index
为负值,则从末尾开始获取元素。越界访问数组将导致运行时错误,从编辑器中运行时会暂停项目执行。