首页 > 解决方案 > 这段代码中的while循环有什么作用?

问题描述

这段代码中的while循环有什么作用?

while 循环是如何工作的?

let numApples = Math.random() * 10;
    
while (numApples > 0) {
    
    console.log("Giving away an apple");
    
    numApples = numApples - 1;
    
}
    
console.log("No apples remaining!");

标签: javascript

解决方案


基本上在伪代码中它执行以下操作。

initiate variable called numApples with a random number 0 - 10.
Then while that number is greater than zero, 
  Output a message to the console saying "Giving away an apple" then
  Subtract one from the numApples number.

Finally when the numApples becomes equal to zero 
  Output a message to the console saying "No apples remaining!"

推荐阅读