var testArr = [6,3,5,1,2,4]copy Print Values and Sum
Print each array value and the sum so far The expected output will be:
Num 6, Sum 6 Num 3, Sum 9 Num 5, Sum 14 Num 1, Sum 15 Num 2, Sum 17 Num 4, Sum 21
How would I write this?
It can be accomplished using reduce
var testArr = [6, 3, 5, 1, 2, 4]; testArr.reduce((total, num) => { console.log(`Num ${num}`); total += num; console.log(`Sum ${total}`); return total; }, 0);
You can use a simple for loop to resolve this.
At each stage of the for loop, you run code, going from left to right in the array.
As such, you can just add each number in the array to a total, and print the total each time something is added:
Code below, sections in //
are comments that do not run but explain what is happening
var total =0; // Set the starting sum to 0
var testArr = [6,3,5,1,2,4]; // Get our array
for(var i=0; i< testArr.length; i++){ //i starts at 0, and grows 1 each loop
total+=testArr[i]; // for testArr[i] each loop, add that number to total
console.log("Num " = testArr[i]+" Sum:"+total); // Print the current value here
}
var testArr = [6,3,5,1,2,4]; for(let i = 0; i<testArr.length; i++){ console.log("Num", testArr[i]); let sum = 0; for(let j = 0; j<=i; j++) { sum += testArr[j]; } console.log("Sum", sum); }
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.