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_programming_lists_basic_operations.htm
廣告
© . All rights reserved.