我如何阅读 freecodecamp 中的 "for-loop" 代码
How do I read this "for-loop" code from freecodecamp
这基本上就是代码,我已经得到了正确的答案,但我只是想弄清楚这个过程是如何工作的
total = 20
var myArr = [ 2,3,4,5,6];
var total = 0;
for (var d = 0; d < myArr.length; d++){
total += myArr[d];
}
我做到了
var myArr = [ 2,3,4,5,6];
var total = "";
for (var d = 0; d < myArr.length; d++){
total += myArr;
}
输出是....(总计是 ="";所以我可以看到里面发生了什么但是..
total= 2,3,4,5,62,3,4,5,62,3,4,5,6
然后我把 myArr 改成了 d
var myArr = [ 2,3,4,5,6];
var total = 0;
for (var d = 0; d < myArr.length; d++){
total += d;
}
为什么
total = 10?
我已将评论添加到您的工作解决方案中,如下所示。
//Create new array to store our range
var myArr = [ 2,3,4,5,6];
//create new variable to store our total at the end
var total = 0;
//repeat code within when d < the length (or number of values) in our array, increment d each time it runs
for (var d = 0; d < myArr.length; d++){
//take the current total and add the current value in our array to it each time
// first time it will be 0 (total) + 2 (myArr[0]) second time it will be 2 (total) + 3 (myArr[1]) and so on.
total += myArr[d];
}
正如另一位用户在您的第二次尝试中指出的那样,您已将总计的数据类型从数字更改为字符串。
一审:
var myArr = [ 2,3,4,5,6];
var total = 0;
for (var d = 0; d < myArr.length; d++){
total += myArr[d];
}
您正在循环范围之外创建一个新变量,该变量仅为 0。当您遍历每次迭代时,您将数组的当前索引 (myArr[d]
) 添加到 total
变量。
在你的第二个变量中,你创建了一个空字符串的新变量。 JavaScript 不知道或不关心您正在尝试添加数字,因此它将数字附加到一个空字符串,因此是您的结果。
var myArr = [ 2,3,4,5,6];
var total = "";
for (var d = 0; d < myArr.length; d++){
total += myArr;
}
+=
运算符适用于字符串和数字,并且根据值的不同表现不同。
0 + '1' - 2 + '-3' // "-1-3"
0 + '1' - 2 // -1
这基本上就是代码,我已经得到了正确的答案,但我只是想弄清楚这个过程是如何工作的
total = 20
var myArr = [ 2,3,4,5,6];
var total = 0;
for (var d = 0; d < myArr.length; d++){
total += myArr[d];
}
我做到了
var myArr = [ 2,3,4,5,6];
var total = "";
for (var d = 0; d < myArr.length; d++){
total += myArr;
}
输出是....(总计是 ="";所以我可以看到里面发生了什么但是..
total= 2,3,4,5,62,3,4,5,62,3,4,5,6
然后我把 myArr 改成了 d
var myArr = [ 2,3,4,5,6];
var total = 0;
for (var d = 0; d < myArr.length; d++){
total += d;
}
为什么
total = 10?
我已将评论添加到您的工作解决方案中,如下所示。
//Create new array to store our range
var myArr = [ 2,3,4,5,6];
//create new variable to store our total at the end
var total = 0;
//repeat code within when d < the length (or number of values) in our array, increment d each time it runs
for (var d = 0; d < myArr.length; d++){
//take the current total and add the current value in our array to it each time
// first time it will be 0 (total) + 2 (myArr[0]) second time it will be 2 (total) + 3 (myArr[1]) and so on.
total += myArr[d];
}
正如另一位用户在您的第二次尝试中指出的那样,您已将总计的数据类型从数字更改为字符串。
一审:
var myArr = [ 2,3,4,5,6];
var total = 0;
for (var d = 0; d < myArr.length; d++){
total += myArr[d];
}
您正在循环范围之外创建一个新变量,该变量仅为 0。当您遍历每次迭代时,您将数组的当前索引 (myArr[d]
) 添加到 total
变量。
在你的第二个变量中,你创建了一个空字符串的新变量。 JavaScript 不知道或不关心您正在尝试添加数字,因此它将数字附加到一个空字符串,因此是您的结果。
var myArr = [ 2,3,4,5,6];
var total = "";
for (var d = 0; d < myArr.length; d++){
total += myArr;
}
+=
运算符适用于字符串和数字,并且根据值的不同表现不同。
0 + '1' - 2 + '-3' // "-1-3"
0 + '1' - 2 // -1