---
title: Pętle i iteracje
slug: Web/JavaScript/Guide/Loops_and_iteration
translation_of: Web/JavaScript/Guide/Loops_and_iteration
---
<div>{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Control_flow_and_error_handling", "Web/JavaScript/Guide/Functions")}}</div>

<p class="summary">Za pomocą pętli możemy w łatwy sposób powtarzać pewne czynności. Ten rodział <a href="/en-US/docs/Web/JavaScript/Guide">JavaScript Guide</a> zapoznaje z różnymi rodzajami pętli, dostępnymi w JavaScript.</p>

<p>Możesz myśleć o pętli jak o skomputeryzowanej wersji gry w której mówisz komuś, żeby zrobił X kroków w jedym kierunku a następnie Y kroków w innym; przykład "Zrób 5 kroków na zachód" może być wyrażone za pomocą pętli w ten sposób:</p>

<pre class="brush: js">var step;
for (step = 0; step &lt; 5; step++) {
  // Uruchamia się 5 razy, z wartościami od 0 do 4.
  console.log('Idę na zachód jeden krok');
}
</pre>

<p>Jest wiele różnych rodzajów pętli, lecz zwykle wszystkie robią to samo: powtarzają zadaną akcję pewną ilość razy (liczba powtórzeń może także wynosić 0).  Różne mechanizmy pętli oferują różne sposoby określania początku i końca pętli. W różnych sytuacjach łatwiej jest użyć danego typu pętli niż innego.</p>

<p>Wyrażenia dla pętli obsługiwane w JavaScript:</p>

<ul>
 <li>{{anch("for")}}</li>
 <li>{{anch("do...while")}}</li>
 <li>{{anch("while")}}</li>
 <li>{{anch("label")}}</li>
 <li>{{anch("break")}}</li>
 <li>{{anch("continue")}}</li>
 <li>{{anch("for...in")}}</li>
 <li>{{anch("for...of")}}</li>
</ul>

<h2 id="for"><code>for</code></h2>

<p>Pętla <code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/for">for</a></code> powtarza wykonie instrukcji, dopóki dostarczony warunek nie zwraca false. Pętla for w JavaScript jest podobna do tej z języków Java czy C. Składnia tej pętli wygląda następująco:</p>

<pre class="syntaxbox">for ([wyrażenieInicjalizacji]; [warunek]; [wyrażenieInkrementacji])
  Instrukcja
</pre>

<p>Podczas wykonywania się pętli for, mają miejsce następujące operacje:</p>

<ol>
 <li> Wykonywane jest wyrażenie <code>wyrażenieInicjalizacji</code>, o ile takie istnieje. Zazwyczaj w tym miejscu inicjalizuje się zmienne, które posłużą później jako liczniki dla pętli.</li>
 <li> Sprawdzana jest wartość zwracana przez wyrażenie <code>warunek</code>, jeśli jest to true, pętla będzie wykonywać się dalej. Jeśli z kolei będzie to false, pętla zostanie przerwana. W przypadku nie podania żadnego wyrażenia warunkowego, pętla będzie traktować to jako true.</li>
 <li>Wykonuje się <code>Instrukcja</code>.  W celu wykonania wielu instrukcji w jednym przebiegu pętli, należy je zgrupować i umieścić w bloku ( <code>{ ... }</code> ).</li>
 <li> Wykonywane zostaje <code>wyrażenie inkrementacji</code>, o ile istnieje. W tym miejscu powiększamy wartość licznika pętli.</li>
 <li>Zarządzanie pętlą wraca do kroku 2.</li>
</ol>

<h3 id="Przykład"><strong>Przykład</strong></h3>

<p>Następująca funkcja zawiera pętle <code>for</code>, która zlicza elementy &lt;option&gt; w rozwijalnej liście &lt;select&gt;. W pętli zostaje zadeklarowana zmienna <code>i</code> z wartością 0. Sprawdza czy <code>i</code> jest mniejsze niż liczba elementów &lt;option&gt;, wykonuje kod wewnątrz i zwiększa wartość <code>i </code>po każdym przebiegu.</p>

<pre class="brush: html">&lt;form name="selectForm"&gt;
  &lt;p&gt;
    &lt;label for="musicTypes"&gt;Choose some music types, then click the button below:&lt;/label&gt;
    &lt;select id="musicTypes" name="musicTypes" multiple="multiple"&gt;
      &lt;option selected="selected"&gt;R&amp;B&lt;/option&gt;
      &lt;option&gt;Jazz&lt;/option&gt;
      &lt;option&gt;Blues&lt;/option&gt;
      &lt;option&gt;New Age&lt;/option&gt;
      &lt;option&gt;Classical&lt;/option&gt;
      &lt;option&gt;Opera&lt;/option&gt;
    &lt;/select&gt;
  &lt;/p&gt;
  &lt;p&gt;&lt;input id="btn" type="button" value="How many are selected?" /&gt;&lt;/p&gt;
&lt;/form&gt;

&lt;script&gt;
function howMany(selectObject) {
  var numberSelected = 0;
  for (var i = 0; i &lt; selectObject.options.length; i++) {
    if (selectObject.options[i].selected) {
      numberSelected++;
    }
  }
  return numberSelected;
}

var btn = document.getElementById("btn");
btn.addEventListener("click", function(){
  alert('Number of options selected: ' + howMany(document.selectForm.musicTypes))
});
&lt;/script&gt;

</pre>

<h2 id="do...while"><code>do...while</code></h2>

<p><code><font face="Open Sans, Arial, sans-serif">Pętla </font><a href="/en-US/docs/Web/JavaScript/Reference/Statements/do...while">do...while</a></code> powtarza <code>instrukcje</code> wewnątrz, dopóki <code>warunek</code> nie zwróci false. Wygląda to następująco:</p>

<pre class="syntaxbox">do
  instrukcja
while (warunek);
</pre>

<p>Możemy skorzystać z wyrażenia bloku (<code>{ ... }</code>), by zgrupować wiele instrukcji. Na końcu wykonywania instrukcji sprawdzany jest warunek. Jeśli zwróci on true, Pętla wykonan się po raz kolejny, z kolei false przerwie pętle. Warto zwrócić uwagę, że ze względu na miejsce umieszczenia warunku, zawsze wykona się ona przynajmniej raz.</p>

<h3 id="Przykład_2"><strong>Przykład</strong></h3>

<p>W tym przykładzie pętla będzie iterawoć do momentu kiedy licznik <code>i</code> nie będzie większy od 5.</p>

<pre class="brush: js">do {
  i += 1;
  console.log(i);
} while (i &lt; 5);</pre>

<h2 id="while"><code>while</code></h2>

<p>Pętla <code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/while">while</a></code> wykonuje się dopóki podany warunek zwraca true. Składnia jest następująca:</p>

<pre class="syntaxbox">while (warunek)
  instrukcja
</pre>

<p>Jeśli <code>warunek</code> zwróci false, pętla zostaje zatrzymana. W odróżniu od pętli <code>do ... while</code>, sprawdzania warunku mamy na początku. Oznacza to, że jeśli warunek na start zwraca name false, pętla nie wykona się ani razu.</p>

<p>W tym przypadku również możemy zgrupować instrukcje za pomocą (<code>{ ... }</code>).</p>

<h3 id="Przykład_1"><strong>Przykład 1</strong></h3>

<p>Następująca pętla <code>while</code> iteruje tak długo aż n jest mniejszy od 3:</p>

<pre class="brush: js">n = 0;
x = 0;
while (n &lt; 3) {
  n++;
  x += n;
}
</pre>

<p>Z każdą iteracją, pętla inkrementuje wartość n i dodaje ją do x. W związku z tym x i n przyjmują następujące wartości:</p>

<ul>
 <li>Po pierwszym przebiegu: n = 1 i x = 1</li>
 <li>Po drugim przebiegu: n = 2 i x = 3</li>
 <li>Po trzecim przebiegu: n = 3 i x = 6</li>
</ul>

<p>Po wykonaniu trzeciego przebiegu, warunek n &lt; 3 nie zwraca już dłużej true, więc pętla zostaje przerwana.</p>

<h3 id="Przykład_2_2"><strong>Przykład 2</strong></h3>

<p>Unikaj nieskończonych pętli. Upewnij się, że podany warunek ma możliwośc zwrócenia false; w przeciwnym razie pętla nigdy nie zostanie przerwana, co w najgorszym razie spowoduje zawieszenie przeglądarki.</p>

<p>Poniższy przykład przedstawia pętla, która nigdy nie zostanie przerwana, ponieważ podany warunek zawsze zwróci true:</p>

<pre class="brush: js">while (true) {
  console.log("Hello, world");
}</pre>

<h2 id="label_statement"><code>label</code> statement</h2>

<p>A <a href="/en-US/docs/Web/JavaScript/Reference/Statements/label">label</a> provides a statement with an identifier that lets you refer to it elsewhere in your program. For example, you can use a label to identify a loop, and then use the <code>break</code> or <code>continue</code> statements to indicate whether a program should interrupt the loop or continue its execution.</p>

<p>The syntax of the label statement looks like the following:</p>

<pre class="syntaxbox">label :
   statement
</pre>

<p>The value of <code><em>label</em></code> may be any JavaScript identifier that is not a reserved word. The <code><em>statement</em></code> that you identify with a label may be any statement.</p>

<h3 id="Example"><strong>Example</strong></h3>

<p>In this example, the label <code>markLoop</code> identifies a <code>while</code> loop.</p>

<pre class="brush: js">markLoop:
while (theMark == true) {
   doSomething();
}</pre>

<h2 id="break_statement"><code>break</code> statement</h2>

<p>Use the <code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/break">break</a></code> statement to terminate a loop, <code>switch</code>, or in conjunction with a label statement.</p>

<ul>
 <li>When you use <code>break</code> without a label, it terminates the innermost enclosing <code>while</code>, <code>do-while</code>, <code>for</code>, or <code>switch</code> immediately and transfers control to the following statement.</li>
 <li>When you use <code>break</code> with a label, it terminates the specified labeled statement.</li>
</ul>

<p>The syntax of the <code>break</code> statement looks like this:</p>

<ol>
 <li><code>break;</code></li>
 <li><code>break <em>label</em>;</code></li>
</ol>

<p>The first form of the syntax terminates the innermost enclosing loop or <code>switch</code>; the second form of the syntax terminates the specified enclosing label statement.</p>

<h3 id="Example_1"><strong>Example</strong> <strong>1</strong></h3>

<p>The following example iterates through the elements in an array until it finds the index of an element whose value is <code>theValue</code>:</p>

<pre class="brush: js">for (i = 0; i &lt; a.length; i++) {
  if (a[i] == theValue) {
    break;
  }
}</pre>

<h3 id="Example_2_Breaking_to_a_label"><strong>Example 2: </strong>Breaking to a label</h3>

<pre class="brush: js">var x = 0;
var z = 0
labelCancelLoops: while (true) {
  console.log("Outer loops: " + x);
  x += 1;
  z = 1;
  while (true) {
    console.log("Inner loops: " + z);
    z += 1;
    if (z === 10 &amp;&amp; x === 10) {
      break labelCancelLoops;
    } else if (z === 10) {
      break;
    }
  }
}
</pre>

<h2 id="continue_statement"><code>continue</code> statement</h2>

<p>The <code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/continue">continue</a></code> statement can be used to restart a <code>while</code>, <code>do-while</code>, <code>for</code>, or <code>label</code> statement.</p>

<ul>
 <li>When you use <code>continue</code> without a label, it terminates the current iteration of the innermost enclosing <code>while</code>, <code>do-while</code>, or <code>for</code> statement and continues execution of the loop with the next iteration. In contrast to the <code>break</code> statement, <code>continue</code> does not terminate the execution of the loop entirely. In a <code>while</code> loop, it jumps back to the condition. In a <code>for</code> loop, it jumps to the <code>increment-expression</code>.</li>
 <li>When you use <code>continue</code> with a label, it applies to the looping statement identified with that label.</li>
</ul>

<p>The syntax of the <code>continue</code> statement looks like the following:</p>

<ol>
 <li><code>continue;</code></li>
 <li><code>continue </code><em><code>label;</code></em></li>
</ol>

<h3 id="Example_1_2"><strong>Example 1</strong></h3>

<p>The following example shows a <code>while</code> loop with a <code>continue</code> statement that executes when the value of <code>i</code> is three. Thus, <code>n</code> takes on the values one, three, seven, and twelve.</p>

<pre class="brush: js">i = 0;
n = 0;
while (i &lt; 5) {
  i++;
  if (i == 3) {
    continue;
  }
  n += i;
}
</pre>

<h3 id="Example_2"><strong>Example 2</strong></h3>

<p>A statement labeled <code>checkiandj</code> contains a statement labeled <code>checkj</code>. If <code>continue</code> is encountered, the program terminates the current iteration of <code>checkj</code> and begins the next iteration. Each time <code>continue</code> is encountered, <code>checkj</code> reiterates until its condition returns <code>false</code>. When <code>false</code> is returned, the remainder of the <code>checkiandj</code> statement is completed, and <code>checkiandj</code> reiterates until its condition returns <code>false</code>. When <code>false</code> is returned, the program continues at the statement following <code>checkiandj</code>.</p>

<p>If <code>continue</code> had a label of <code>checkiandj</code>, the program would continue at the top of the <code>checkiandj</code> statement.</p>

<pre class="brush: js">checkiandj:
  while (i &lt; 4) {
    console.log(i);
    i += 1;
    checkj:
      while (j &gt; 4) {
        console.log(j);
        j -= 1;
        if ((j % 2) == 0) {
          continue checkj;
        }
        console.log(j + " is odd.");
      }
      console.log("i = " + i);
      console.log("j = " + j);
  }</pre>

<h2 id="for...in_statement"><code>for...in</code> statement</h2>

<p>The <a href="/en-US/docs/Web/JavaScript/Reference/Statements/for...in"><code>for...in</code></a> statement iterates a specified variable over all the enumerable properties of an object. For each distinct property, JavaScript executes the specified statements. A <code>for...in</code> statement looks as follows:</p>

<pre class="syntaxbox">for (variable in object) {
  statements
}
</pre>

<h3 id="Example_3"><strong>Example</strong></h3>

<p>The following function takes as its argument an object and the object's name. It then iterates over all the object's properties and returns a string that lists the property names and their values.</p>

<pre class="brush: js">function dump_props(obj, obj_name) {
  var result = "";
  for (var i in obj) {
    result += obj_name + "." + i + " = " + obj[i] + "&lt;br&gt;";
  }
  result += "&lt;hr&gt;";
  return result;
}
</pre>

<p>For an object <code>car</code> with properties <code>make</code> and <code>model</code>, <code>result</code> would be:</p>

<pre class="brush: js">car.make = Ford
car.model = Mustang
</pre>

<h3 id="Arrays"><strong>Arrays</strong></h3>

<p>Although it may be tempting to use this as a way to iterate over {{jsxref("Array")}} elements, the <strong>for...in</strong> statement will return the name of your user-defined properties in addition to the numeric indexes. Thus it is better to use a traditional <code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/for">for</a></code> loop with a numeric index when iterating over arrays, because the <strong>for...in</strong> statement iterates over user-defined properties in addition to the array elements, if you modify the Array object, such as adding custom properties or methods.</p>

<h2 id="for...of_statement"><code>for...of</code> statement</h2>

<p>The <code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/for...of">for...of</a></code> statement creates a loop Iterating over <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/iterable">iterable objects</a> (including {{jsxref("Array")}}, {{jsxref("Map")}}, {{jsxref("Set")}}, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope/arguments">arguments</a> object and so on), invoking a custom iteration hook with statements to be executed for the value of each distinct property.</p>

<pre class="syntaxbox">for (<em>variable</em> of <em>object</em>) {
  <em>statement
</em>}</pre>

<p>The following example shows the difference between a <code>for...of</code> loop and a <code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/for...in" title="en-US/docs/JavaScript/Reference/Statements/for...in">for...in</a></code> loop. While <code>for...in</code> iterates over property names, <code>for...of</code> iterates over property values:</p>

<pre class="brush:js">let arr = [3, 5, 7];
arr.foo = "hello";

for (let i in arr) {
   console.log(i); // logs "0", "1", "2", "foo"
}

for (let i of arr) {
   console.log(i); // logs "3", "5", "7"
}
</pre>

<p>{{PreviousNext("Web/JavaScript/Guide/Control_flow_and_error_handling", "Web/JavaScript/Guide/Functions")}}</p>