Dart 程式設計 - 更新列表



更新索引

Dart 允許修改列表中專案的 值。換句話說,可以重寫列表項的值。以下示例說明了這一點:

void main() { 
   List l = [1, 2, 3,]; 
   l[0] = 123;
   print (l);
}

以上示例更新了索引為 0 的列表項的值。程式碼的輸出將為:

[123, 2, 3]

使用 List.replaceRange() 函式

來自 dart:core 庫的 List 類提供replaceRange()函式來修改列表項。此函式替換指定範圍內的元素的值。

使用 List.replaceRange() 函式的語法如下所示:

List.replaceRange(int start_index,int end_index,Iterable <items>)

其中,

  • Start_index - 表示開始替換的索引位置的整數。

  • End_index - 表示停止替換的索引位置的整數。

  • <items> - 表示更新值的 iterable 物件。

以下示例說明了這一點:

即時演示
void main() {
   List l = [1, 2, 3,4,5,6,7,8,9];
   print('The value of list before replacing ${l}');
   
   l.replaceRange(0,3,[11,23,24]);
   print('The value of list after replacing the items between the range [0-3] is ${l}');
}

它應該產生以下輸出

The value of list before replacing [1, 2, 3, 4, 5, 6, 7, 8, 9]
The value of list after replacing the items between the range [0-3] is [11, 23, 24, 4, 5, 6, 7, 8, 9]
dart_programming_lists_basic_operations.htm
廣告

© . All rights reserved.