Dart刪除列表項

dart:core庫中List類支持的以下函數可用於刪除List中的專案。

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]

List.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]

List.removeLast()

List.removeLast()函數彈出並返回List中的最後一項。語法如下 -

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列表 下一篇: Dart映射