在 Dart 中获取集合/列表中数字总和的最简洁方法是什么? [英] What is the cleanest way to get the sum of numbers in a collection/list in Dart?

查看:12
本文介绍了在 Dart 中获取集合/列表中数字总和的最简洁方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不喜欢使用索引数组,因为我认为它看起来很丑.有没有一种用匿名函数求和的干净方法?不使用任何外部变量是否可以做到这一点?

I don't like using an indexed array for no reason other than I think it looks ugly. Is there a clean way to sum with an anonymous function? Is it possible to do it without using any outside variables?

推荐答案

Dart 迭代现在有一个 reduce 函数 (https://code.google.com/p/dart/issues/detail?id=1649),所以你可以在不定义自己的折叠函数的情况下简单地做一个总结:

Dart iterables now have a reduce function (https://code.google.com/p/dart/issues/detail?id=1649), so you can do a sum pithily without defining your own fold function:

var sum = [1, 2, 3].reduce((a, b) => a + b);

这篇关于在 Dart 中获取集合/列表中数字总和的最简洁方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆