镖。不能'改变列表的元素

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)

Nut*_*uts 6

如果您希望替换/更新列表 ( 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)


Ran*_*rtz 5

您无法更改函数或 var-in 循环的参数。您可以对它们调用方法,这可能会产生改变它们的副作用,但直接分配给它们不会改变它们被有效复制的值。


Bla*_*nka 5

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)