JavaScript中的循环
我确切地知道如何编写for循环和while循环,但是我很难理解后面的内容。例如,我做了一个交互式教程,要求我编写一个For循环,将数字1添加到10 这是for循环的语法:JavaScript中的循环,javascript,loops,Javascript,Loops,我确切地知道如何编写for循环和while循环,但是我很难理解后面的内容。例如,我做了一个交互式教程,要求我编写一个For循环,将数字1添加到10 这是for循环的语法: { var currentSum = 0; for (var i=1; i<= num; i++) { currentSum += i; // <-- } return current sum // <-- } console.log(sum(10)) {
{
var currentSum = 0;
for (var i=1; i<= num; i++) {
currentSum += i; // <--
}
return current sum // <--
}
console.log(sum(10))
{
var currentSum=0;
对于带注释的(var i=1;i1)currentSum+=i;//,这有帮助吗
function sum(num) <-- you seem to be missing this
{
var currentSum = 0; // <-- declare variable and assign it to 0
for (var i=1; i<= num; i++) { // <--start a loop, with i as the counter,
// starting at 1 and finishing at whatever
// the value of num is
currentSum += i; // <-- take the current value of currentSum and
// add i to it, shorthand way of writing
// currentSum = currentSum + i
}
//return current sum // <-- This line is completely wrong
return currentSum; // <-- Return the variable currentSum after all the
// looping and summing has finished
}
//consol.long(sum(10)); // <-- this line is also wrong, there is no such
// thing as consol.long
console.log(sum(10)); // <-- should be console.log, which is outputting
// the return value of the function call sum,
// passing in a value of 10 as the input
// parameter num, to the console.
// Which in most browsers, can be located via F12
函数和(num)
2*-->这里似乎有点不正确。空格不应该在那里。您正在从函数返回计算值。这甚至不是有效的javascript。请发布一些有效的内容,至少可以运行。代码中似乎缺少函数的开头?它不应该以函数sum(num)开头吗
return currentSum // will return the final value.
function sum(num) <-- you seem to be missing this
{
var currentSum = 0; // <-- declare variable and assign it to 0
for (var i=1; i<= num; i++) { // <--start a loop, with i as the counter,
// starting at 1 and finishing at whatever
// the value of num is
currentSum += i; // <-- take the current value of currentSum and
// add i to it, shorthand way of writing
// currentSum = currentSum + i
}
//return current sum // <-- This line is completely wrong
return currentSum; // <-- Return the variable currentSum after all the
// looping and summing has finished
}
//consol.long(sum(10)); // <-- this line is also wrong, there is no such
// thing as consol.long
console.log(sum(10)); // <-- should be console.log, which is outputting
// the return value of the function call sum,
// passing in a value of 10 as the input
// parameter num, to the console.
// Which in most browsers, can be located via F12
function sum(n)
{
var currentSum = 0;
for (var i=1; i<=num; i++) {
currentSum += i; // <-- 1*
}
return currentSum; // <-- 2*
}
currentSum = currentSum + i