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