Something like this but generalized
let arr = [6, 5, 4, 3];
let i = 0, j = 0;
let result = [];
result.push(arr[0]+arr[1],
arr[2]+arr[3]);
console.log(result
Ignoring last element if array has odd number of elements:
function f(arr) { let result = []; for (let i=0; i<arr.length; i++) { if (i % 2==0 && i<arr.length-1) { result.push(arr[i] + arr[i+1]); i++; } }; return result; } let arr = [6, 5, 4, 3]; console.log(f(arr)); console.log(f([1, 2, 3, 4, 5, 6, 7]));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.