简体   繁体   中英

Trying to add each element of array to the next one for unknown number of elements

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM