Dart 编程 - 删除列表项


dart:core 库中的 List 类支持的以下函数可用于删除列表中的项目。

列表.remove()

List.remove() 函数删除列表中第一次出现的指定项目。如果指定值已从列表中删除,则此函数返回 true。

句法

List.remove(Object value)

在哪里,

  • value - 表示应从列表中删除的项目的值。

以下示例展示了如何使用此功能 -

void main() { 
   List l = [1, 2, 3,4,5,6,7,8,9]; 
   print('The value of list before removing the list element ${l}'); 
   bool res = l.remove(1); 
   print('The value of list after removing the list element ${l}'); 
}

它将产生以下输出 -

The value of list before removing the list element [1, 2, 3, 4, 5, 6, 7, 8, 9] 
The value of list after removing the list element [2, 3, 4, 5, 6, 7, 8, 9] 

列表.removeAt()

List.removeAt函数删除指定索引处值并返回它。

句法

List.removeAt(int index)

在哪里,

  • index - 表示应从列表中删除的元素的索引。

以下示例展示了如何使用此功能 -

void main() { 
   List l = [1, 2, 3,4,5,6,7,8,9]; 
   print('The value of list before removing the list element ${l}'); 
   dynamic res = l.removeAt(1); 
   print('The value of the element ${res}'); 
   print('The value of list after removing the list element ${l}'); 
} 

它将产生以下输出 -

The value of list before removing the list element [1, 2, 3, 4, 5, 6, 7, 8, 9] 
The value of the element 2 
The value of list after removing the list element [1, 3, 4, 5, 6, 7, 8, 9] 

列表.removeLast()

List.removeLast ()函数弹出并返回列表中的最后一项。其语法如下所示 -

List.removeLast()

以下示例展示了如何使用此功能 -

void main() { 
   List l = [1, 2, 3,4,5,6,7,8,9]; 
   print('The value of list before removing the list element ${l}');  
   dynamic res = l.removeLast(); 
   print('The value of item popped ${res}'); 
   print('The value of list after removing the list element ${l}'); 
}

它将产生以下输出 -

The value of list before removing the list element [1, 2, 3, 4, 5, 6, 7, 8, 9] 
The value of item popped 9 
The value of list after removing the list element [1, 2, 3, 4, 5, 6, 7, 8] 

List.removeRange()

List.removeRange ()函数删除指定范围内的项目。其语法如下所示 -

List.removeRange(int start, int end)

在哪里,

  • Start - 表示删除项目的起始位置。

  • End - 表示列表中停止删除项目的位置。

以下示例展示了如何使用此功能 -

void main() { 
   List l = [1, 2, 3,4,5,6,7,8,9]; 
   print('The value of list before removing the list element ${l}'); 
   l.removeRange(0,3); 
   print('The value of list after removing the list 
      element between the range 0-3 ${l}'); 
}

它将产生以下输出 -

The value of list before removing the list element 
   [1, 2, 3, 4, 5, 6, 7, 8, 9] 
The value of list after removing the list element 
   between the range 0-3 [4, 5, 6, 7, 8, 9]
dart_programming_lists_basic_operations.htm