假设我在下面的数组中有一些数字
let numberArray = [1, 3, 4, 6, 9, 14, 16]
Run Code Online (Sandbox Code Playgroud)
我知道如何使用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]
Run Code Online (Sandbox Code Playgroud)
我应该用什么方法来实现这个目标?
提前致谢.
您可以使用dropFirst(_:)或使用范围作为索引.
如果它不是固定数字,您可以先使用它firstIndex(of:)来确定要启动的索引.
numberArray.dropFirst(3).reduce(0, +)
numberArray[3...].reduce(0, +)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
447 次 |
| 最近记录: |