当前位置: 首页 > 文档资料 > Dart 中文教程 >

删除列表项(Removing List items)

优质
小牛编辑
137浏览
2023-12-01

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

List.remove()

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

语法 (Syntax)

List.remove(Object value)

Where,

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

以下example显示如何使用此功能 -

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] 

List.removeAt()

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

语法 (Syntax)

List.removeAt(int index)

Where,

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

以下example显示如何使用此功能 -

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] 

List.removeLast()

List.removeLast()函数弹出并返回List中的最后一项。 相同的语法如下 -

List.removeLast()

以下example显示如何使用此功能 -

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)

Where,

  • 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]