JavaScript waa mid ka mid ah luqadaha barnaamijyada ugu caansan ee loo adeegsado horumarinta webka iyo codsiyada kale. Mid ka mid ah waxyaabaha muhiimka ah ee luqadda JavaScript waa awoodda ay u leedahay in ay la shaqeyso loops, taas oo fududeynaysa in xariiqyo badan oo kood ah la fuliyo si aan la isku dhibin. Waxaad isticmaali kartaa loops si aad koodkaaga uga dhigto mid wax ku ool ah oo aan dib loo soo celin dhowr jeer. Waxaa jira saddex nooc oo loop ah oo caadi ah JavaScript, kuwaas oo kala ah: for
, while
, iyo do...while
.
Loops in JavaScript - for, while, do...while |
1. for
Loop
for
loop waa mid ka mid ah loops-ka ugu caansan ee barnaamijyada. Waxa uu ku shaqeeyaa iyadoo loo marayo xaalad cad oo ku saabsan xisaabaadka. Inta badan waxa loo isticmaalaa markaad taqaan tirada saxda ah ee wareegyada (iterations) aad rabto inaad fuliso.
Syntax:
javascript
for (let i = 0; i < 5; i++) {
console.log(i);
}
Kor, loop-ka wuxuu bilaabayaa i=0 wuxuuna soconayaa ilaa i ay ka gaadho 5. Xaaladda i++ waxay kordhisaa qiimaha i markiiba halkii wareeg (iteration). Output-ku wuxuu noqon doonaa 0 ilaa 4, oo tusinaya inta jeer ee loop-ku shaqeeyay.
2. while
Loop
while
loop waxa uu soconayaa ilaa xaalad la siiyay ay run tahay. Loop-ka noocan ah waxa uu ku fiican yahay marka aadan hubin tirada jeer ee aad rabto in loop-ka socdo.
Syntax:
javascript
let i = 0;
while (i < 5) {
console.log(i);
i++;
}
Marka xaaladda i < 5
ay run tahay, loop-ka wuxuu sii socon doonaa ilaa uu ka gaadho xaalad been ah. Waxaa loo baahan yahay in qiimaha i la kordhiyo wareeg kasta, haddii kale loop-ku wuxuu gali doonaa wareeg aan dhamaad lahayn.
3. do...while
Loop
do...while
loop waa mid la mid ah while
, laakiin farqi yar ayaa jira: do...while
loop wuxuu fulin doonaa ugu yaraan hal jeer, xitaa haddii xaaladdu ay marka hore been tahay.
Syntax:
javascript
let i = 0;do {
console.log(i);
i++;
} while (i < 5);
Loop-kan wuxuu xitaa fulin doonaa haddii xaaladda lagu siiyay while ay marka hore been tahay. Tani waxay faa'iido leedahay marka aad rabto in ugu yaraan hal jeer la fuliyo xariiqda koodka, ka hor inta aan la hubin xaaladda.
Gabagabo
Loops waa hab wax ku ool ah oo aad si fudud ugu maareyn karto wareegyo badan oo hawlaha barnaamijyada. Isticmaalka for
, while
, iyo do...while
waxay kaa caawin karaan inaad koodkaaga u habeyso hab dhakhso leh oo fudud, iyadoo ku xiran xaaladda aad ku sugan tahay. Fahamka noocyada kala duwan ee loops-ka ayaa kaa dhigi kara barnaamije yaqaan karti badan leh.