javascript - 如何使用替代变量编写这个 for 循环?

标签 javascript

我是初学者,这是类作业。所以,如果你愿意的话,请给我一些指示。我需要找到答案,但我被困住了。说明:

function exerciseTwo(){
  let count = 0;

  // In this exercise write your own for loop (you can look at the syntax above). 
  // It should loop 10 times.
  // You are given a variable called: count .
  // For each loop reassign count to the current value of count + 1 .


  //Please write your answer in the line above. 
  return count;
}

我所有可能的答案都因运行测试失败而返回:

for (let count = 0; count < 10; count++) {

     console.log ("count");
   }
for (let count = 0; count < 10; i++) {

     console.log ("count");
   } 

在这个例子中,我认为我应该创建一些变量来提供帮助。我知道它们可能行不通。但是,本着尝试的精神。

function exerciseTwo(){
  let count = 0;
  let count = i;
  let i = 0
  // In this exercise write your own for loop (you can look at the syntax above). 
  // It should loop 10 times.
  // You are given a variable called: count .
  // For each loop reassign count to the current value of count + 1 .
   for (let i = 0; i < 10; i++) {

     console.log ("i");
   }

最佳答案

您可以直接获取 count 并使用 while 循环检查该值是否小于 10。

您的代码的问题是,您将局部变量 count 作为嵌套范围,这不会更改外部 count

function x() {
    let count = 0;
    while (count < 10) ++count;
    return count;
}

console.log(x());

通过查看 for statement ,你得到它的四部分

for ([initialization]; [condition]; [final-expression])
   statement
  • 初始化,这里不需要,因为你已经声明并初始化了变量count,它在for 语句。

  • 条件是检查变量是否为某个值。如果解析为 true 或为 truthy值,则循环继续。

  • final-expression 它用于更新循环因变量,但它可以包含多个表达式。上述所有部分都可以包含多个表达式。

  • statement 这里是一个空语句,仅用分号 ; 表示。通常有一个声明或block {} statement ,即将多个语句分组。

function x() {
    let count = 0;
    for (; count < 10; ++count) ;
    return count;
}

console.log(x());

关于javascript - 如何使用替代变量编写这个 for 循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54632641/

相关文章:

javascript - 是否可以在 javascript 中找到 dom 节点的自定义滚动条 css 属性?

javascript - 如何在选中指向网站页面的链接后制作 2 个下拉选项

javascript - JavaScript ES6 类中的私有(private)属性

javascript - Google Docs 如何在 JavaScript 中全屏显示

javascript - 如何在登录后请求用户数据,Node.JS

javascript - 仅当用户接受 cookie 政策时,Google 跟踪代码管理器才会触发代码

javascript - Express JS 无法识别环境

javascript - 带有 ES6 的 Angular 1.5.0 - Controller 导出不工作

javascript - 根据年份范围过滤对象

javascript - AngularJS 不重新加载部分 jQuery 脚本