javascript - 如何累积每个数字?JavaScript
问题描述
这是我的问题 我很难解决这个问题 任务:我们将向您传递一个包含两个数字的数组。返回这两个数字的总和加上它们之间所有数字的总和。最低的数字并不总是排在第一位。
For example, sumAll([4,1]) should return 10 because
sum of all the numbers between 1 and 4 (both inclusive) is 10.
function sumAll(arr) {
Math.min(arr); //finds the lowest number and takes it 1
Math.max(arr); //finds the largest number 4
//must start at the 1st number and loops over until the max value is reached
//0 start at the 0th index of the array
//++ increament by one so 1 2 3 4
//multiply's each number
//.lenght until the lenght of the array is reached
var i;
for (i = 0; i < arr.length; i++) {
i * i;
}
return 1;
}
sumAll([1, 4]);
解决方案
如果数组中总是有 2 个数字,那么您可以轻松地做到这一点,而无需更多花哨的代码。
var arr = [1, 4];
arr.sort((a, b) => a - b);
var total = 0;
for (var i = arr[0]; i <= arr[1]; i++ ) {
total += i;
}
console.log(total);
推荐阅读
- opencv - 读取 OpenCV FOURCC 代码 int 到 char 转换
- javascript - 在移动浏览器中使用 go 键跳过 HTML“日期”输入
- python - 在 Python 中对 2 个数组进行 t 测试时获取数组而不是数字
- function - 参数类型“Function”不能分配给参数类型“void Function(bool?)?”。空对象
- javascript - JavaScript 中模块的执行上下文是什么?如何在浏览器的控制台中显式访问它?
- python - 通过 SQL Server 代理作业在 Conda 中使用 Numpy 运行 python 脚本
- sql - 来自 SQL 源的 BIT 列由数据收集器转换为布尔值
- css - Material-UI Grid - 自动堆叠项目以占用最小垂直空间
- pandas - Pandas - 在不复制数据的情况下计算行数
- css - 2021 年 CSS 动画最佳实践是什么,以确保与所有浏览器兼容?