arrays - 从特定元素添加数组中的快速求和数
问题描述
假设我在下面的数组中有一些数字
let numberArray = [1, 3, 4, 6, 9, 14, 16]
我知道如何通过使用 reduce 方法来总结它们,但是如何开始从特定元素添加数字。例如:
//Sum all up by reduce
let sumAll = numberArray.reduce(0, +)
//sumAll = 53
//I want to start counting from the fourth element in the array which is 6
//so the total should be 45. [6 + 9 + 14 + 16]
我应该使用什么方法来实现这一点?
提前致谢。
解决方案
您可以使用dropFirst(_:)
或使用范围作为索引。
如果它不是一个固定的数字,你可以先用它firstIndex(of:)
来确定你想要开始的索引。
numberArray.dropFirst(3).reduce(0, +)
numberArray[3...].reduce(0, +)
推荐阅读
- excel - 我想从组合框中选择数据并使用 VBA Excel 中的 IF 语句将其拉到我的按钮
- python - 如何使这 2 个字符串匹配算法更有效?
- scala - 如何禁用所有 Scala 类型提示?
- .net - 更改 applicationUrl 后 IIS 服务器连接问题
- python - Groupby 名称用所有列中的最大值替换值 pandas
- swift - MeasurementFormatter 删除零并返回为 Double
- java - 调用 httpclient.execute(httpPost) 时出现 sslhandshake 问题
- django - SerializerMethodField 未显示 - Django Rest Framework
- teradata - 如何仅获取不匹配的数据
- powerbi - LOOP 在 M Query 中查找值