Jac*_*k J 3 arrays collections loops list dart
我无法使用匿名函数更改数组元素:
var collection=[0, 1, 2];
collection.forEach((c)=> c+=1);
print(collection);
Run Code Online (Sandbox Code Playgroud)
此变体也不起作用:
var collection = [0, 1, 2];
for (var x in collection) {
x=x+1;
}
print(collection);
Run Code Online (Sandbox Code Playgroud)
如果您希望替换/更新列表 ( List<int> items = [1, 2, 3]) 中的所有项目:
items = items.map((x) => x + 1).toList();
for (int i = 0; i < items.length; i++) items[i] += 1;
items = List<int>.generate(items.length, (i) => items[i] + 1);
List<int> tempItems = [];
items.forEach((x) => tempItems.add(x + 1));
items = tempItems;
Run Code Online (Sandbox Code Playgroud)
collection.forEach((c)=> c+=1);
Run Code Online (Sandbox Code Playgroud)
在上面的行中,您将参数增加 1,这不会影响列表。
它相当于:
collection.forEach((int c) {// in this case int because list contains int's
c = c + 1;
});
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,更改参数(局部变量)的值没有意义。
既然是0,1,2,你可以这样做:collection.forEach((c)=> collection[c] = c+1);。这是愚蠢的方法,因为每当您更改任何值时,您都会收到错误(超出范围)。
因此,您可以通过以下一些方法更改列表值:
最简单的方法:
void main() {
var collection=[0, 1, 2];
for(int i = 0; i < collection.length; i++) {
collection[i] += 1;
}
print(collection);
}
Run Code Online (Sandbox Code Playgroud)
使用replaceRange:
void main() {
var collection=[0, 1, 2];
var temp = collection.map((c) => c+1).toList();
collection.replaceRange(0, collection.length, temp);
print(collection);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11957 次 |
| 最近记录: |