Indexes in Dart
Every element in the List
, or String
, has a unique address. Such addresses are called indexes:
Indexes start from 0. The first element is assigned the index 0, the second element is assigned the index 1, and so on.
We can retrieve an element from the list using its index with the following syntax:
listName[index]
Example
Let's print the element at index 1 from the List
:
main.dart
1234void main() { List<String> names = ["Bob", "John"]; print(names[1]); // John }
Editing
Dart allows modifying the value of an item in a List
. In other words, you can re-write the value of a List
item.
main.dart
12345void main() { List cars = ["BMW", "Porsche", "Ford"]; cars[0] = "Toyota"; print(cars); // ["Toyota", "Porsche", "Ford"] }
The above example updates the value of the List item with index 0. The output of the code will be − ["Toyota", "Porsche", "Ford"]
.
String Indexes
In a String
, we also have indexes.
main.dart
1234void main() { String user = "Alex"; print(user[0]); }
1. Select the element at index 1 in the string 'Codefinity'.
2. What will the following code output?
Tak for dine kommentarer!
Spørg AI
Spørg AI
Spørg om hvad som helst eller prøv et af de foreslåede spørgsmål for at starte vores chat
Awesome!
Completion rate improved to 4.55
Indexes in Dart
Stryg for at vise menuen
Every element in the List
, or String
, has a unique address. Such addresses are called indexes:
Indexes start from 0. The first element is assigned the index 0, the second element is assigned the index 1, and so on.
We can retrieve an element from the list using its index with the following syntax:
listName[index]
Example
Let's print the element at index 1 from the List
:
main.dart
1234void main() { List<String> names = ["Bob", "John"]; print(names[1]); // John }
Editing
Dart allows modifying the value of an item in a List
. In other words, you can re-write the value of a List
item.
main.dart
12345void main() { List cars = ["BMW", "Porsche", "Ford"]; cars[0] = "Toyota"; print(cars); // ["Toyota", "Porsche", "Ford"] }
The above example updates the value of the List item with index 0. The output of the code will be − ["Toyota", "Porsche", "Ford"]
.
String Indexes
In a String
, we also have indexes.
main.dart
1234void main() { String user = "Alex"; print(user[0]); }
1. Select the element at index 1 in the string 'Codefinity'.
2. What will the following code output?
Tak for dine kommentarer!