我一开始完全不懂迴圈是怎么操作的,看了别人的解题方法,也不懂为什么这样写,就会重複呢?
JavaScript有三种迴圈,怎么知道什么情况下用哪种迴圈?
JavaScript 中的三种迴圈
JavaScript 中有三种迴圈,分别是for、while、do..while
,在实作中最常用到的是for、while
迴圈。
所有的迴圈都必须包含:
1.初始值(begin)
2.终止条件(condition)当终止条件为 false 时停止迴圈
3.递增或递减的方式(step)
4.循环体(do):每一迴圈要做的事情。
。迭代:每进入一次循环体我们就称为“一次迭代”,假设进入三次就称为三次迭代。
。参考文章:[第四週] JavaScript — 迴圈(Loop)while、for,如果想要学习更详细的迴圈内容,可以参考这篇文章,我觉得他写的浅显易懂,受益良多。
这篇要来讲解我学习while
迴圈的Tip!
while题目:
### TaskCoding in function padIt, function accept 2 parameters:str, it's a string representing the string to pad, we need pad some "*" at leftside or rightside of strn, it's a number, how many times to pad the string.### BehaviourYou need to write a loop statement within the function that loops n times. Each time through the loop it will add one * to str, alternating on which side it is padded: the first time will add a * to the left side of str, the second time will add a * to the right side, and so on.### Solutionfunction padIt(str,n){}
这题我卡很久,因为我知道如何印出文字,但不知道如何让他重複显示,这时就要来说明一下解题思路:
首先:要如何判断单数及双数?
假设 i 是一个数字
let i = 1;if(i%2 === 1){ console.log("我是单数");}else{ console.log("我是双数");}
% 是取余数的意思,上面那段语法的意思就是“如果数字i 除以2 余数等于1的话(=== 是严格相等的意思),显示我是单数,否则显示我是双数”
第二步:解决左右要如何显示*
?
let i = 1;let returnStr = str;if(i%2 === 1){ returnStr = "*" + returnStr; }else{ returnStr = returnStr + "*"; }
第三步:完整while写法
function padIt(str,n){ let i = 1; let returnStr = str; while (i<=n){ if(i%2 === 1){ returnStr = "*" + returnStr; }else{ returnStr = returnStr + "*"; } i++; } return returnStr;}
i++
是什么呢?就是前面讲到的“递增或递减的方式”i++
是递增,i--
就是递减啰!