Dart可以修改List中專案的值。換句話說,可以重寫列表項的值。如下所示 -
void main() {
List l = [1, 2, 3,];
1[0] = 123;
print (1);
}
上面的示例更新List中索引為0
項的值。執行上面示例代碼,得到以下結果:
[123, 2, 3]
使用List.replaceRange()函數
dart:core庫中的List類提供了replaceRange()
函數來修改List
項。此函數替換指定範圍內元素的值。
使用List.replaceRange()
函數的語法如下 -
List.replaceRange(int start_index,int end_index,Iterable <items>)
其中,
start_index
- 表示要開始替換的索引位置的整數。end_index
- 表示要停止替換的索引位置的整數。<items>
- 表示更新值的可迭代對象。
參考以下示例代碼 -
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]