我很困惑。为什么在下面的代码块中i + = 1打印输出12x,但是i + = 2只打印6次?不应该这样吗? (我的大脑今天不工作。)
function printManyTimes(str) {
"use strict";
const SENTENCE = str + " is cool!";
for (let i = 0; i < str.length; i += 2 ) {
console.log(SENTENCE);
}
}
printManyTimes("freeCodeCamp");
答案 0 :(得分:4)
当i
小于 str.length
时循环。
如果您将i
的增加速度提高一倍,那么它会变成str.length
的一半时间。
答案 1 :(得分:2)
因为您每次迭代都将迭代器推进两个单元
答案 2 :(得分:0)
此处是代码的修改版本,用于显示 for循环的工作方式。昆汀的回答很好地解释了这一点。
function printManyTimes(str, amountToIncrement) {
"use strict";
const SENTENCE = str + " is cool!";
for (let i = 0; i < str.length; i += amountToIncrement ) {
console.log(SENTENCE + " " + i);
}
}
console.log("increment amount as 1")
printManyTimes("freeCodeCamp", 1);
console.log("increment amount as 2")
printManyTimes("freeCodeCamp", 2);
console.log("increment amount as 3")
printManyTimes("freeCodeCamp", 3);
console.log("increment amount as .5")
printManyTimes("freeCodeCamp", .5);
答案 3 :(得分:0)
function printManyTimes(str) {
"use strict";
const SENTENCE = str + " is cool!"; // freeCodeCamp is cool!
for (let i = 0; i < str.length; i += 2 ) {
// if i+=2 in your loop the console log run only while i = [0, 2, 4, 6, 8, 10] - 6 times
// if i+=1/i++ in your loop the console log run only while i = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] - 12 times
console.log(SENTENCE);
}
}
printManyTimes("freeCodeCamp"); // freeCodeCamp length = 12
这是数组的基础知识。您可以在https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for
中找到更多信息。