javascript - How to add value two by two in array?
问题描述
I want to make array that contain numbers into new array which has sum result of two by two.
For example, if there is number array like below
const arrayOne = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
I want to change it like below
const newArrayOne = [1, 5, 9, 13, 17]
other example is
const arrayTwo = [10, 11, 12, 13, 14, 15]
const newArrayTwo = [21, 25, 29]
How can I achieve this?
解决方案
您可以简单地通过for
迭代来完成。
const arrayOne = [10, 11, 12, 13, 14, 15, 17]
const result = [];
for(var i = 0; i < arrayOne.length; i+=2){
const sum = arrayOne[i] + ((i + 1 < arrayOne.length) ? arrayOne[i + 1] : 0);
result.push(sum);
}
console.log(result)
推荐阅读
- intellij-idea - Intellij 播放/调试按钮消失
- php - 如何将 Blade 模板文件扩展名从 *.blade.php 更改为仅 *.blade
- maximo - 在应用程序的列表视图中突出显示记录的技术术语是什么?
- c++ - 使用 GMP 库运行 C++ 程序以使用大数导致错误:C4146: unary minus operator applied to unsigned type, result still unsigned
- python - 查找多次之间的时间差
- javascript - Enzyme wrapper.update() 导致 ref 输入不再具有 value prop
- swift - 调整 iPhone 和 iPad 中视频的帧大小
- javascript - 当空气到达右下角时,算法不能正确地杀死棋子
- swift - 删除边缘并从 PDFView 滚动
- rust - 我应该如何减少 rust 类型签名的重复?