Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/dart/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Dart 如何对列表中的所有项调用函数?_Dart - Fatal编程技术网

Dart 如何对列表中的所有项调用函数?

Dart 如何对列表中的所有项调用函数?,dart,Dart,是否有一种惯用方法将函数应用于列表中的所有项 例如,在Python中,假设我们希望将列表中的所有字符串大写,我们可以使用循环: regimentNames = ['Night Riflemen', 'Jungle Scouts', 'The Dragoons', 'Midnight Revengence', 'Wily Warriors'] # create a variable for the for loop results regimentNamesCapitalized_f = []

是否有一种惯用方法将函数应用于列表中的所有项

例如,在Python中,假设我们希望将列表中的所有字符串大写,我们可以使用循环:

regimentNames = ['Night Riflemen', 'Jungle Scouts', 'The Dragoons', 'Midnight Revengence', 'Wily Warriors']
# create a variable for the for loop results
regimentNamesCapitalized_f = []

# for every item in regimentNames
for i in regimentNames:
    # capitalize the item and add it to regimentNamesCapitalized_f
    regimentNamesCapitalized_f.append(i.upper())
但更简洁的方法是:

capitalizer = lambda x: x.upper()
regimentNamesCapitalized_m = list(map(capitalizer, regimentNames)); regimentNamesCapitalized_m

在Dart中对列表中的所有项目调用函数的等效方法是什么?

答案似乎是使用匿名函数,或者将函数传递给lists
forEach
方法

传递函数:

void capitalise(var string) {
  var foo = string.toUpperCase();
  print(foo);
}

var list = ['apples', 'bananas', 'oranges'];
list.forEach(capitalise);
list.forEach((item){
  print(item.toUpperCase());
});
使用匿名函数:

void capitalise(var string) {
  var foo = string.toUpperCase();
  print(foo);
}

var list = ['apples', 'bananas', 'oranges'];
list.forEach(capitalise);
list.forEach((item){
  print(item.toUpperCase());
});
如果函数只在一个地方使用,我认为最好使用匿名函数,因为很容易阅读列表中发生的事情


如果要在多个位置使用该函数,则最好传递该函数,而不是使用匿名函数。

如果要将函数应用于
列表中的所有项(或
Iterable
)并收集结果,Dart提供了一个与Python的
map
等效的
Iterable.map
函数:

//省道
ComunityNamesCapitalized_m=ComunityNames.map((x)=>x.toUpperCase()).toList();
Python还提供列表理解,这通常被认为更像Python,并且通常比函数式方法更受欢迎:

#Python
ComunityNamesCapitalized_m=[x.upper()表示ComunityNames中的x]
Dart相当于Python的列表理解的集合是:

//省道
ComunityNamesCapitalized_m=[用于(ComunityNames中的变量x)x.toUpperCase()];
如果您调用函数是因为函数的副作用,而不关心其返回值,则可以使用
Iterable.forEach
而不是
Iterable.map
。然而,在这种情况下:

  • 我认为它们更容易阅读,因为它们更普通
  • 它们更灵活。您可以使用
    break
    continue
    来控制迭代
  • 他们可能会更有效率
    .forEach
    涉及每次迭代调用一个额外的函数来调用提供的回调

奇怪的是,您的Python示例使用了
map
,但您没有使用
List.map
您的Dart代码,这是一个直接的模拟。这里的示例也与Python版本不同,因为Python版本生成列表,但这里您只是打印每个元素。@jamesdlin我的问题的重点是讨论将函数传递给列表中所有项的有效方法。你的问题要求“一种等价的方式”,所以在我看来,你应该提供等价的代码,尤其是因为这样做很简单。