Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
95 views
in Technique[技术] by (71.8m points)

javascript - How to create function that add numbers in array using "while" loop?

I have an exercise to create a function (lets call it "iterateAndSum") which will sum all numbers in array and return the result. I can't use reduce (which is easier). I have to focus on using while loop.

I tried and failed miserably:

function iterateAndSum(arr) {
    while (i--) {
        e += arr[i]; 
    }
}
question from:https://stackoverflow.com/questions/65900995/how-to-create-function-that-add-numbers-in-array-using-while-loop

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
function iterateAndSum(arr) {
  let i = 0;
  let e = 0;
  while (i < arr.length) {
    e += arr[i];
    i++;
  }
  return e;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...