JavaScript中的函数和循环

bxgwgixi  于 2024-01-05  发布在  Java
关注(0)|答案(1)|浏览(150)

我在练习JavaScript中的函数和循环。

  1. var i;
  2. var result = '';
  3. function candy(x) {
  4. for (i = 0; i <= 2; i++) {
  5. console.log(x + " candy. Take 1, " + (x - 1) + " candy.");
  6. }
  7. return result += i;
  8. }
  9. candy(4);

字符串
输出:

  1. "4 candy, Take 1 down, 3 candy"
  2. "4 candy, Take 1 down, 3 candy"
  3. "4 candy, Take 1 down, 3 candy"
  4. "3"


我的预期输出:

  1. "4 candy, Take 1 down, 3 candy"
  2. "3 candy, Take 1 down, 2 candy"
  3. "2 candy, Take 1 down, 1 candy"


我在我的循环中错过了什么吗?任何建议?谢谢!

pgpifvop

pgpifvop1#

在你的循环中,你使用的是(x - 1),这需要改为(x - i)。原因是x被初始化为4。每次循环运行时,它输出4 - 1。如果你使用(x - i),这将每次递减...试试下面的代码:

  1. var i;
  2. var result = '';
  3. function candy(x) {
  4. for (i = 0; i <= 2; i++) {
  5. console.log(x + " candy. Take 1, " + (x - i) + " candy.");
  6. }
  7. return result += i;
  8. }
  9. candy(4);

字符串
如果你想删除糖果,在循环中使用x--;。

  1. var i;
  2. var result = '';
  3. function candy(x) {
  4. for (i = 0; i <= 2; i++) {
  5. console.log(x + " candy. Take 1, " + (--x) + " candy.");
  6. }
  7. return result += i;
  8. }
  9. candy(4);

展开查看全部

相关问题