Dart- 传播运算符(...)
在Dart中,Spread Operator (...) 和 Null-aware Spread Operator (...?) 用于在集合中插入多个元素,例如 Lists、Maps 等。
语法:
- 扩展运算符
...Data_structure
- 空感知传播运算符
...?Data_structure
示例 1:将扩展运算符与List一起使用。
Dart
// main function start
void main() {
// initialise a List l1
List? l1 = ["Geeks","For","Geeks"];
// initialize another List l2 using l1
List? l2=["Wow",...l1,"is","amazing"];
// print List l2
print(l2);
}
Dart
// main function start
void main() {
// initialise a Map m1
Map? m1 = {"name":"John","age":21};
// initialize another Map m2 using m1
Map? m2={"roll no":45,"class":12,...m1};
// print Map m2
print(m2);
}
Dart
// main function start
void main() {
// first set s1
Set s1 = {5, 4, 3};
// second set s2
Set s2 = {3, 2, 1};
// result Set
Set result = {...s1, ...s2};
// print result set
print(result);
}
输出 :
[Wow, Geeks, For, Geeks, is, amazing]
示例 2:将 Spread运算符与Map一起使用。
Dart
// main function start
void main() {
// initialise a Map m1
Map? m1 = {"name":"John","age":21};
// initialize another Map m2 using m1
Map? m2={"roll no":45,"class":12,...m1};
// print Map m2
print(m2);
}
输出 :
{roll no: 45, class: 12, name: John, age: 21}
示例 3:将扩展运算符与集合一起使用。
Dart
// main function start
void main() {
// first set s1
Set s1 = {5, 4, 3};
// second set s2
Set s2 = {3, 2, 1};
// result Set
Set result = {...s1, ...s2};
// print result set
print(result);
}
输出:
{5,4,3,2,1}