Dart刪除列表項

2019-10-16 22:07:13

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]