From de5c456ebded0e038adbf23db34cc290c8829180 Mon Sep 17 00:00:00 2001 From: Florian Merz Date: Thu, 11 Feb 2021 14:49:24 +0100 Subject: unslug pl: move --- .../reference/statements/async_function/index.html | 264 ++++++++++++++++++ .../reference/statements/block/index.html | 160 +++++++++++ .../reference/statements/break/index.html | 67 +++++ .../reference/statements/class/index.html | 113 ++++++++ .../reference/statements/const/index.html | 53 ++++ .../reference/statements/continue/index.html | 166 +++++++++++ .../reference/statements/debugger/index.html | 126 +++++++++ .../reference/statements/do...while/index.html | 54 ++++ .../reference/statements/empty/index.html | 92 ++++++ .../reference/statements/export/index.html | 47 ++++ .../reference/statements/for...in/index.html | 173 ++++++++++++ .../javascript/reference/statements/for/index.html | 58 ++++ .../reference/statements/function/index.html | 68 +++++ .../reference/statements/function_star_/index.html | 309 +++++++++++++++++++++ .../reference/statements/if...else/index.html | 65 +++++ .../reference/statements/import/index.html | 55 ++++ .../web/javascript/reference/statements/index.html | 149 ++++++++++ .../reference/statements/label/index.html | 51 ++++ .../reference/statements/return/index.html | 48 ++++ .../reference/statements/switch/index.html | 285 +++++++++++++++++++ .../reference/statements/throw/index.html | 197 +++++++++++++ .../javascript/reference/statements/var/index.html | 61 ++++ .../reference/statements/while/index.html | 61 ++++ 23 files changed, 2722 insertions(+) create mode 100644 files/pl/web/javascript/reference/statements/async_function/index.html create mode 100644 files/pl/web/javascript/reference/statements/block/index.html create mode 100644 files/pl/web/javascript/reference/statements/break/index.html create mode 100644 files/pl/web/javascript/reference/statements/class/index.html create mode 100644 files/pl/web/javascript/reference/statements/const/index.html create mode 100644 files/pl/web/javascript/reference/statements/continue/index.html create mode 100644 files/pl/web/javascript/reference/statements/debugger/index.html create mode 100644 files/pl/web/javascript/reference/statements/do...while/index.html create mode 100644 files/pl/web/javascript/reference/statements/empty/index.html create mode 100644 files/pl/web/javascript/reference/statements/export/index.html create mode 100644 files/pl/web/javascript/reference/statements/for...in/index.html create mode 100644 files/pl/web/javascript/reference/statements/for/index.html create mode 100644 files/pl/web/javascript/reference/statements/function/index.html create mode 100644 files/pl/web/javascript/reference/statements/function_star_/index.html create mode 100644 files/pl/web/javascript/reference/statements/if...else/index.html create mode 100644 files/pl/web/javascript/reference/statements/import/index.html create mode 100644 files/pl/web/javascript/reference/statements/index.html create mode 100644 files/pl/web/javascript/reference/statements/label/index.html create mode 100644 files/pl/web/javascript/reference/statements/return/index.html create mode 100644 files/pl/web/javascript/reference/statements/switch/index.html create mode 100644 files/pl/web/javascript/reference/statements/throw/index.html create mode 100644 files/pl/web/javascript/reference/statements/var/index.html create mode 100644 files/pl/web/javascript/reference/statements/while/index.html (limited to 'files/pl/web/javascript/reference/statements') diff --git a/files/pl/web/javascript/reference/statements/async_function/index.html b/files/pl/web/javascript/reference/statements/async_function/index.html new file mode 100644 index 0000000000..95b488405e --- /dev/null +++ b/files/pl/web/javascript/reference/statements/async_function/index.html @@ -0,0 +1,264 @@ +--- +title: funkcja async +slug: Web/JavaScript/Referencje/Polecenia/funkcja_async +translation_of: Web/JavaScript/Reference/Statements/async_function +--- +
+
{{jsSidebar("Statements")}}
+ +

Deklaracja funkcji async definiuje funkcję asynchroniczną, która zwraca obiekt  {{jsxref("Global_Objects/AsyncFunction","AsyncFunction")}}. Funkcja asynchroniczna to funkcja, która działa asynchroniczne poprzez zdarzenie pętli używając bezwarunkowego {{jsxref("Promise")}} do zwrócenia wyniku. Składnia i struktura kodu używanego przy funkcjach asynchronicznych jest jednakże bardziej podobna do znanych ze standardowych funkcji synchronicznych.

+ +
+

Możesz zdefiniować funkcje asynchroniczne również poprzez użycie {{jsxref("Operators/async_function", "async function expression", "", 1)}}.

+
+
+ +
{{EmbedInteractiveExample("pages/js/statement-async.html", "taller")}}
+ + + +

Składnia

+ +
async function name([param[, param[, ... param]]]) {
+   statements
+}
+
+ +

Parametry

+ +
+
name
+
Nazwa funkcji.
+
+ +
+
param
+
Nazwa argumentu, który zostanie podany do funkcji.
+
+ +
+
statements
+
Wyrażenia stanowiące ciało funkcji.
+
+ +

Wartość zwrotna (return)

+ +

Promise, które zostanie rozwiązane z wartością zwróconą przez funkcję asynchroniczną lub odrzucone z nieprzechwyconym wyjątkiem wyrzuconym z funkcji asynchronicznej.

+ +

Opis

+ +

Funkcja async może zawierać wyrażenie {{jsxref("Operators/await", "await")}}, które wstrzymuje wywołanie funkcji asynchronicznej i czeka na przekazaną deklarację Promisei wtedy wznawia wywołanie funkcji async oraz interpretuje jako wartość rozwiązaną.
+
+ Pamiętaj, że polecenie await działa wyłącznie wewnątrz funkcji async. Jeśli użyjesz go poza ciałem funkcji async otrzymasz SyntaxError.

+ +

Zauważ, że kiedy funkcja async jest wstrzymana, funkcja wywołująca kontynuuje działanie (otrzymując domyślny Promise zwracany przez funkcję async).

+ +
+

Celem funkcji async/await jest uproszczenie działania używając obietnic (promises) synchronicznie oraz by wykonać pewne działania w grupie Promises. Tak, jak Promises są podobne do strukturalnych callbacków, tak async/await jest podobne do kombinacji generatorów i obietnic.

+
+ +

Przykłady

+ +

Prosty przykład

+ +
var resolveAfter2Seconds = function() {
+  console.log("starting slow promise");
+  return new Promise(resolve => {
+    setTimeout(function() {
+      resolve("slow");
+      console.log("wolna obietnica została wykonana");
+    }, 2000);
+  });
+};
+
+var resolveAfter1Second = function() {
+  console.log("starting fast promise");
+  return new Promise(resolve => {
+    setTimeout(function() {
+      resolve("fast");
+      console.log("szybka obietnica została wykonana");
+    }, 1000);
+  });
+};
+
+var sequentialStart = async function() {
+  console.log('==START SEKWENCYJNY==');
+
+  // 1. Niemalże natychmiast dochodzi do wywołania
+  const slow = await resolveAfter2Seconds();
+  console.log(slow); // 2. to zostaje wywołanie 2s po 1.
+
+  const fast = await resolveAfter1Second();
+  console.log(fast); // 3. to zostaje wykonane 3s po 1.
+}
+
+var concurrentStart = async function() {
+  console.log('==RÓWNOCZESNY START z await==');
+  const slow = resolveAfter2Seconds(); // licznik startuje od razu
+  const fast = resolveAfter1Second(); // licznik startuje od razu
+
+  // 1. Niemalże natychmiast dochodzi do wywołania
+  console.log(await slow); // 2. jest wywołane 2s po 1.
+  console.log(await fast); // 3. jest wywołane 2s po 1., natychmiast po 2., podczas gdy szybka jest już wykonana
+}
+
+var concurrentPromise = function() {
+  console.log('==RÓWNOCZESNY START z Promise.all==');
+  return Promise.all([resolveAfter2Seconds(), resolveAfter1Second()]).then((messages) => {
+    console.log(messages[0]); // wolne
+    console.log(messages[1]); // szybkie
+  });
+}
+
+var parallel = async function() {
+  console.log('==RÓWNOLEGLE z await Promise.all==');
+
+  // Równolegle startują dwa zadania i czekamy na zakończenie działania obu
+  await Promise.all([
+      (async()=>console.log(await resolveAfter2Seconds()))(),
+      (async()=>console.log(await resolveAfter1Second()))()
+  ]);
+}
+
+// This function does not handle errors. See warning below!
+var parallelPromise = function() {
+  console.log('==PARALLEL with Promise.then==');
+  resolveAfter2Seconds().then((message)=>console.log(message));
+  resolveAfter1Second().then((message)=>console.log(message));
+}
+
+sequentialStart(); // after 2 seconds, logs "slow", then after 1 more second, "fast"
+
+// wait above to finish
+setTimeout(concurrentStart, 4000); // after 2 seconds, logs "slow" and then "fast"
+
+// wait again
+setTimeout(concurrentPromise, 7000); // same as concurrentStart
+
+// wait again
+setTimeout(parallel, 10000); // truly parallel: after 1 second, logs "fast", then after 1 more second, "slow"
+
+// wait again
+setTimeout(parallelPromise, 13000); // same as parallel
+
+ +
+

await and parallelism

+ +

In sequentialStart, execution suspends 2 seconds for the first await, and then again another 1 second for the second await. The second timer is not created until the first has already fired. The code finishes after 3 seconds.

+ +

In concurrentStart, both timers are created and then awaited. The timers are running concurrently, which means the code finishes in 2 rather than 3 seconds, i.e. the slowest timer.
+ However the await calls are still running in series, which means the second await will wait for the first one to finish. In this case, this leads to the processing of the result of the fastest timer to be performed after the slowest.

+ +

If you wish to fully perform two or more jobs in parallel, you must use await Promise.all([job1(), job2()]) as shown in the parallel example.

+
+ +
+

async/await vs Promise#then and error handling

+ +

Most async functions can also be written as regular functions using Promises. However async functions are a little bit less error-prone when it comes to error handling.

+ +

Both concurrentStart and concurrentPromise are functionally equivalent.
+ In concurrentStart, if either of the awaited calls fail, the exception will be automatically caught, the async function execution interrupted, and the Error propagated to the caller through the implicit return Promise.
+ For the same to happen in the Promise case, the function must take care of returning a Promise which captures the completion of the function. In concurrentPromise that means returning the promise from Promise.all([]).then(). As a matter of fact, a previous version of this example forgot to do this!

+ +

It is however still possible for async functions to mistakenly swallow errors.
+ Take for example the parallel async function. If it didn't await (or return) the result of the Promise.all([]) call, any Error would not have been propagated.
+ While the parallelPromise example seem simple, it does not handle errors at all! Doing so would require a similar return Promise.all([]).

+
+ +

Rewriting a promise chain with an async function

+ +

An API that returns a {{jsxref("Promise")}} will result in a promise chain, and it splits the function into many parts. Consider the following code:

+ +
function getProcessedData(url) {
+  return downloadData(url) // returns a promise
+    .catch(e => {
+      return downloadFallbackData(url); // returns a promise
+    })
+    .then(v => {
+      return processDataInWorker(v); // returns a promise
+    });
+}
+
+ +

it can be rewritten with a single async function as follows:

+ +
async function getProcessedData(url) {
+  let v;
+  try {
+    v = await downloadData(url);
+  } catch(e) {
+    v = await downloadFallbackData(url);
+  }
+  return processDataInWorker(v);
+}
+
+ +

Note that in the above example, there is no await statement on the return statement, because the return value of an async function is implicitly wrapped in {{jsxref("Promise.resolve")}}.

+ +
+

return await promiseValue; vs. return promiseValue;

+ +

The implicit wrapping of return values in {{jsxref("Promise.resolve")}} does not imply that return await promiseValue; is functionally equivalent to return promiseValue;

+ +

Consider the following rewrite of the above code that returns null if processDataInWorker were to reject with an error:

+ +
async function getProcessedData(url) {
+  let v;
+  try {
+    v = await downloadData(url);
+  } catch(e) {
+    v = await downloadFallbackData(url);
+  }
+  try {
+    return await processDataInWorker(v); // Note the `return await` vs. just `return`
+  } catch (e) {
+    return null;
+  }
+}
+
+ +

Having simply written return processDataInWorker(v); would have caused the {{jsxref("Promise")}} returned by the function to reject instead of resolving to null in the case where processDataInWorker(v) rejects. This highlights the subtle difference between return foo; and return await foo; which is that return foo; will immediately return foo and never throw even if foo is a promise and rejects whereas return await foo; will wait for foo to resolve or reject if it's a promise and will throw before returning if it rejects.

+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-async-function-definitions', 'async function')}}{{Spec2('ESDraft')}}Initial definition in ES2017.
{{SpecName('ES8', '#sec-async-function-definitions', 'async function')}}{{Spec2('ES8')}}
+ +

Browser compatibility

+ +
+ + +

{{Compat("javascript.statements.async_function")}}

+
+ +

See also

+ + diff --git a/files/pl/web/javascript/reference/statements/block/index.html b/files/pl/web/javascript/reference/statements/block/index.html new file mode 100644 index 0000000000..bbc5c7e4fb --- /dev/null +++ b/files/pl/web/javascript/reference/statements/block/index.html @@ -0,0 +1,160 @@ +--- +title: block +slug: Web/JavaScript/Referencje/Polecenia/block +tags: + - Dokumentacja_JavaScript + - Dokumentacje + - JavaScript + - Wszystkie_kategorie +translation_of: Web/JavaScript/Reference/Statements/block +--- +

Blok instrukcji jest stosowany do zgrupowania zero lub więcej instrukcji. Blok jest ograniczony parą nawiasów klamrowych i opcjonalnie może posiadać etykietę.

+ +

Składnia

+ +

Blok

+ +
{ ListaInstrukcji }
+
+ +

Blok z etykietą

+ +
EtykietaBloku: { ListaInstrukcji }
+ +

Parametry

+ +
+
ListaInstrukcji
+
Instrukcje zgrupowane w bloku.
+
EtykietaBloku
+
Opcjonalna etykieta dla wizualnej identyfikacji lub jako cel dla break.
+
+ +

Opis

+ +

Blok instrukcji nazywany jest również w innych językach instrukcjami złożonymi. Pozwala użyć wielu instrukcji tam, gdzie JavaScript pozwala użyć tylko jednej. Składanie instrukcji w bloki jest powszechną praktyką w JavaScript. Za pomocą bloku można uzyskać też efekt przeciwny - brak instrukcji tam, gdzie jest wymagana.

+ +

Reguły zasięgu bloku

+ +

Zasięg var

+ +

Zmienne tworzone poprzez var nie mają zasięgu bloku. Zmienne zadeklarowane w bloku są ograniczone do funkcji lub skryptu zawierającego, a efektyoperacji na nich utrzymują się poza samym blokiem. Innymi słowy, instrukcje blokowe nie wprowadzają zakresu. Chociaż "samodzielne" bloki są poprawną składnią, nie chcesz używać niezależnych bloków w JavaScript, ponieważ nie robią tego, co myślisz, że robią, jeśli myślisz, że robią coś takiego jak w C lub Java. Na przykład:

+ +
var x = 1;
+{
+  var x = 2;
+}
+console.log(x); // zwraca 2
+
+ +

Otrzymujesz 2, ponieważ instrukcja var x = 2, która jest w bloku jest w tym samym zasięgu co instrukcja przed blokiem. W C lub Javie podobny kod zwróciłby 1.

+ +

Zasięg let i const

+ +

Dla odmiany identyfikatory stworzone z użyciem let i const posiadają zakres blokowy:

+ +
let x = 1;
+{
+  let x = 2;
+}
+console.log(x); // zwraca 1
+
+ +

Instrukcja x = 2 jest ograniczona w zakresie bloku, w którym została zdefiniowana.

+ +

To samo odnosi się do const:

+ +
const c = 1;
+{
+  const c = 2;
+}
+console.log(c); // zwraca 1 i nie rzuca wyjątkiem SyntaxError.
+
+ +

Zauważ, że const c = 2 nie rzuca wyjątku SyntaxError: Identifier 'c' has already been declared, ponieważ może być zadeklarowane unikalnie w ramach bloku.

+ +

Zasięg funkcji

+ +

Funkcja zadeklarowana w bloku również widzialna jest w zakresie tego bloku:

+ +
foo('outside');  // TypeError: foo is not a function
+{
+  function foo(location) {
+   console.log('foo is called ' + location);
+  }
+  foo('inside'); // wykonuje się poprawnie i zwraca 'foo is called inside'
+}
+
+ +

Bardziej precyzyjnie mówiąc blok instrukcji zapobiega Hoistingowi deklaracji funkcji na początek zakresu. Funkcja zachowuje się tak, jakby była zdefiniowana jako wyrażenie funkcji i jako taka jest tylko deklaracją zmiennej, która zostaje podniesiona do góry, na początek zakresu:

+ +
foo;  // zwraca undefined
+{
+  function foo(location) {
+   console.log('foo is called ' + location);
+  }
+  foo('inside'); // wykonuje się poprawnie i zwraca 'foo is called inside'
+}
+ +

Konsekwentnie to znaczy, że gdy przeniesiemy wywołanie funkcji poniżej jej deklaracji - nie otrzymamy błędu:

+ +
{
+  function foo(location) {
+   console.log('foo is called ' + location);
+  }
+  foo('inside'); // works correctly and logs 'foo is called inside'
+}
+foo('outside');  // works correctly and logs 'foo is called outside'
+
+ +

Specyfikacja

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-block', 'Block statement')}}{{Spec2('ESDraft')}} 
{{SpecName('ES6', '#sec-block', 'Block statement')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-12.1', 'Block statement')}}{{Spec2('ES5.1')}} 
{{SpecName('ES3', '#sec-12.1', 'Block statement')}}{{Spec2('ES3')}} 
{{SpecName('ES1', '#sec-12.1', 'Block statement')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
+ +

Kompatybilność z przeglądarkami

+ + + +

{{Compat("javascript.statements.block")}}

+ +

Zobacz także

+ + diff --git a/files/pl/web/javascript/reference/statements/break/index.html b/files/pl/web/javascript/reference/statements/break/index.html new file mode 100644 index 0000000000..661b130d71 --- /dev/null +++ b/files/pl/web/javascript/reference/statements/break/index.html @@ -0,0 +1,67 @@ +--- +title: break +slug: Web/JavaScript/Referencje/Polecenia/break +tags: + - Dokumentacja_JavaScript + - Dokumentacje + - JavaScript + - Wszystkie_kategorie +translation_of: Web/JavaScript/Reference/Statements/break +--- +

+

+

Podsumowanie

+

Przerywa aktualnie wykonywaną pętlę, konstrukcję switch i przekazuje sterowanie programu do polecenia za pętlą lub za wskazaną etykietą. +

+ + + + + + + + + + + + +
Polecenie
Zaimplementowane w:JavaScript 1.0, NES 2.0
Wersja ECMA:ECMA-262 (wersja bez etykiety) +

ECMA-262, Edycja 3 (wersja z etykietą) +

+
+

Składnia

+

+break {{ mediawiki.external('etykieta') }} + +

+

Parametry

+
etykieta 
Identyfikator przypisany etykiecie polecenia. +
+

Opis

+

Polecenie break może zawierać opcjonalną etykietę, która pozwala programowi na wyjście z bloku poleceń oznaczonego etykietą. Polecenia w bloku oznaczonym etykietą mogą być dowolnego rodzaju. +

+

Przykłady

+

Przykład: Zastosowanie break

+

Poniższa funkcja zawiera polecenie break, które przerywa pętlę +while, kiedy e jest równe 3, a następnie zwraca wartość 3 * x. +

+
function testBreak(x) {
+   var i = 0;
+   while (i < 6) {
+      if (i == 3)
+         break;
+      i++;
+   }
+   return i*x;
+}
+
+

Zobacz także

+

continue, +etykieta, +switch +


+


+

+
+
+{{ languages( { "en": "en/Core_JavaScript_1.5_Reference/Statements/break", "es": "es/Referencia_de_JavaScript_1.5/Sentencias/break", "fr": "fr/R\u00e9f\u00e9rence_de_JavaScript_1.5_Core/Instructions/break", "ja": "ja/Core_JavaScript_1.5_Reference/Statements/break" } ) }} diff --git a/files/pl/web/javascript/reference/statements/class/index.html b/files/pl/web/javascript/reference/statements/class/index.html new file mode 100644 index 0000000000..05cdb7b2d4 --- /dev/null +++ b/files/pl/web/javascript/reference/statements/class/index.html @@ -0,0 +1,113 @@ +--- +title: class +slug: Web/JavaScript/Referencje/Polecenia/class +translation_of: Web/JavaScript/Reference/Statements/class +--- +
{{jsSidebar("Statements")}}
+ +
Deklaracja klasy tworzy nową klasę z daną nazwą, używając dziedziczenia opartego na prototypach.
+ +
{{EmbedInteractiveExample("pages/js/statement-class.html")}}
+ + + +
+

Możesz także zdefiniować klasę, używając {{jsxref("Operators/class", "wyrażenia class", "", 1)}}. W odróżnieniu jednak od wyrażenia class, deklaracja klasy nie pozwala na ponowne zadeklarowanie istniejącej klasy i w takim przypadku zwróci błąd.

+
+ +

Składnia

+ +
class nazwa [extends] {
+  // ciało klasy
+}
+
+ +

Opis

+ +

Ciało klasy w deklaracji klasy jest wykonywane w  trybie ścisłym. Konstruktor jest opcjonalny.

+ +

Deklaracje klas nie są {{Glossary("Hoisting", "hoisted")}} (w odróżnieniu od deklaracji funkcji).

+ +

Przykłady

+ +

Prosta deklaracja klasy

+ +

W poniższym przykładzie, najpierw definiujemy klasę o nazwie Polygon, a następnie rozszerzamy ją do klasy Square. Zwróć uwagę na to, że super(), użyte w konstruktorze, może byc użyte jedynie w konstruktorach i musi być wywołane przed użyciem słowa kluczowego this.

+ +
class Polygon {
+  constructor(height, width) {
+    this.name = 'Polygon';
+    this.height = height;
+    this.width = width;
+  }
+}
+
+class Square extends Polygon {
+  constructor(length) {
+    super(length, length);
+    this.name = 'Square';
+  }
+}
+ +
+

Próba podwójnej deklaracji klasy

+ +

Próba ponownego zadeklarowania klasy, przy użyciu deklaracji klasy, spowoduje wystąpienie błędu.

+ +
class Foo {};
+class Foo {}; // Uncaught SyntaxError: Identifier 'Foo' has already been declared
+
+ +

Taki sam błąd jest zwracany, gdy klasa jest zdefiniowana przed użyciem wyrażenia klasy.

+ +
var Foo = class {};
+class Foo {}; // Uncaught TypeError: Identifier 'Foo' has already been declared
+
+
+
+ +

Specyfikacje

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecyfikacjaStatusKomentarz
{{SpecName('ES2015', '#sec-class-definitions', 'Class definitions')}}{{Spec2('ES2015')}}Początkowa definicja.
{{SpecName('ES2016', '#sec-class-definitions', 'Class definitions')}}{{Spec2('ES2016')}}
{{SpecName('ES2017', '#sec-class-definitions', 'Class definitions')}}{{Spec2('ES2017')}}
{{SpecName('ESDraft', '#sec-class-definitions', 'Class definitions')}}{{Spec2('ESDraft')}}
+ +

Wsparcie przeglądarek

+ + + +

{{Compat("javascript.statements.class")}}

+ +

Zobacz też

+ + diff --git a/files/pl/web/javascript/reference/statements/const/index.html b/files/pl/web/javascript/reference/statements/const/index.html new file mode 100644 index 0000000000..ead1ca32fb --- /dev/null +++ b/files/pl/web/javascript/reference/statements/const/index.html @@ -0,0 +1,53 @@ +--- +title: const +slug: Web/JavaScript/Referencje/Polecenia/const +tags: + - Dokumentacja_JavaScript + - Dokumentacje + - JavaScript + - Wszystkie_kategorie +translation_of: Web/JavaScript/Reference/Statements/const +--- +

+

+

Podsumowanie

+

Deklaruje nazwaną stałą tylko do odczytu. +

+ + + + + + + + +
Wyrażenie
Zaimplementowane w:JavaScript 1.5, NES 6.0 (rozszerzenie Netscape, tylko w silniku C)
+

Składnia

+

+const nazwaStałej {{ mediawiki.external('= wartość') }} [..., nazwaStałej {{ mediawiki.external('= wartość') }} ] + +

+

Parametry

+
nazwaStałej 
Nazwa stałej. Może być dowolnym dozwolonym identyfikatorem. +
+
wartość 
Wartość stałej. Może być dowolną dozwoloną wartością lub wynikiem wyrażenia. +
+

Opis

+

Tworzy stałą, która może być globalna lub lokalna dla funkcji, która ją zadeklarowała. Zasady zasięgu dla stałych są takie same jak dla zmiennych. +

Wartość stałej nie może zostać zmieniona poprzez ponowne przypisanie; stała nie może także być ponownie zadeklarowana. +

Stała nie może mieć takiej samej nazwy jak funkcja lub zmienna o tym samym zasięgu. +

+

Przykłady

+

Przykład: Zastosowanie const

+

Poniższy skrypt wypisuje "a jest równe 7". +

+
const a = 7;
+document.writeln("a jest równe " + a);
+
+

Zobacz także

+

var +


+

+
+
+{{ languages( { "en": "en/Core_JavaScript_1.5_Reference/Statements/const", "fr": "fr/R\u00e9f\u00e9rence_de_JavaScript_1.5_Core/Instructions/const", "ja": "ja/Core_JavaScript_1.5_Reference/Statements/const" } ) }} diff --git a/files/pl/web/javascript/reference/statements/continue/index.html b/files/pl/web/javascript/reference/statements/continue/index.html new file mode 100644 index 0000000000..b6c2a05d94 --- /dev/null +++ b/files/pl/web/javascript/reference/statements/continue/index.html @@ -0,0 +1,166 @@ +--- +title: continue +slug: Web/JavaScript/Referencje/Polecenia/continue +tags: + - JavaScript + - instrukcja + - polecenie +translation_of: Web/JavaScript/Reference/Statements/continue +--- +
{{jsSidebar("Statements")}}
+ +

Polecenie continue zatrzymuje wykonanie pętli w obecnej iteracji, w obecnej lub wskazanej pętli i kontynuuje wykonanie pętli w kolejnej jej iteracji.

+ +
{{EmbedInteractiveExample("pages/js/statement-continue.html")}}
+ + + +

Składnia

+ +
continue [etykieta];
+ +
+
etykieta
+
Identyfikator powiązany z etykietą instrukcji.
+
+ +

Opis

+ +

W przeciwieństwie do instrukcji {{jsxref("Statements/break", "break")}}, continue nie zatrzymuje całkowicie wykonania pętli, natomiast:

+ + + + + +

Instrukcja continue może opcjonalnie zawierać etykietę, która pozwala programowi przejść do kolejnej iteracji pętli, której tę etykietę przypisano, zamiast kolejnej iteracji obecnej pętli. W tym przypadku, polecenie continue musi być zawarte wewnątrz instrukcji z etykietą.

+ +

Przykłady

+ +

Użycie continue z while

+ +

Poniższy przykład pokazuje pętlę {{jsxref("Statements/while", "while")}}, zawierającą polecenie continue, które jest wykonywane, gdy wartość zmiennej i równa jest 3 – zatem n przyjmuje kolejno wartości 1, 3, 7 i 12.

+ +
var i = 0;
+var n = 0;
+
+while (i < 5) {
+  i++;
+
+  if (i === 3) {
+    continue;
+  }
+
+  n += i;
+}
+
+ +

Użycie continue z etykietą

+ +

W poniższym przykładzie, instrukcja z etykietą checkiandj zawiera instrukcję z etykietą checkj. Jeśli zostanie napotkane polecenie continue, wykonanie programu jest kontynuowane od góry instukcji checkj. Za każdym razem, gdy napotkane jest continue, chekckj jest przeiterowywane dopóki jego warunek nie zwróci wartości false. Kiedy zwracane jest false, wykonywana jest pozostała część checkiandj.

+ +

Gdyby continue miało etykietę checkiandj, wówczas program powinien przejść na początek instrukcji checkiandj.

+ +

Zobacz też {{jsxref("Statements/label", "label")}}.

+ +
var i = 0;
+var j = 8;
+
+checkiandj: while (i < 4) {
+  console.log('i: ' + i);
+  i += 1;
+
+  checkj: while (j > 4) {
+    console.log('j: ' + j);
+    j -= 1;
+
+    if ((j % 2) == 0)
+      continue checkj;
+    console.log('Liczba' + j + ' jest nieparzysta.');
+  }
+  console.log('i = ' + i);
+  console.log('j = ' + j);
+}
+
+ +

Wyjście:

+ +
i: 0
+
+// początek checkj
+j: 8
+Liczba 7 jest nieparzysta.
+j: 7
+j: 6
+Liczba 5 jest nieparzysta.
+j: 5
+// koniec checkj
+
+i = 1
+j = 4
+
+i: 1
+i = 2
+j = 4
+
+i: 2
+i = 3
+j = 4
+
+i: 3
+i = 4
+j = 4
+
+ +

Specyfikacje

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecyfikacjaStatusUwagi
{{SpecName('ES1')}}{{Spec2('ES1')}}Wstępna definicja. Wersja bez etykiety.
{{SpecName('ES3')}}{{Spec2('ES3')}}Dodano wersję z etykietą.
{{SpecName('ES5.1', '#sec-12.7', 'Continue statement')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-continue-statement', 'Continue statement')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-continue-statement', 'Continue statement')}}{{Spec2('ESDraft')}}
+ +

Wsparcie przeglądarek

+ + + +

{{Compat("javascript.statements.continue")}}

+ +

Zobacz też

+ + diff --git a/files/pl/web/javascript/reference/statements/debugger/index.html b/files/pl/web/javascript/reference/statements/debugger/index.html new file mode 100644 index 0000000000..b4fe9548a7 --- /dev/null +++ b/files/pl/web/javascript/reference/statements/debugger/index.html @@ -0,0 +1,126 @@ +--- +title: debugger +slug: Web/JavaScript/Referencje/Polecenia/debugger +translation_of: Web/JavaScript/Reference/Statements/debugger +--- +
{{jsSidebar("Statements")}}
+ +
Wyrażenie  debugger uruchamia dowolną dostępną funkcjonalność umożliwiającą debuggowanie, przykładowo poprzez ustawienie breakpointa w miejscu użycia wyrażenia. Jeżeli żadna tego typu funkcjonalność nie jest dostępna, użycie wyrażenia nie ma wpływu na działanie programu.
+ +
+

Składnia

+
+ +
debugger;
+ +

Przykłady

+ +

Poniższy przykład pokazuje użycie wyrażenia debugger w celu uruchomienia debuggera w momencie wywołania funkcji (jeżeli jest dostępny).

+ +
function potentiallyBuggyCode() {
+    debugger;
+    // przeprowadź analizę działania programu zawierających bugi, przejdź do kolejnych wywołań, itp.
+}
+ +

Kiedy następuje wywołanie instrukcji debugger, uruchomienie programu zatrzymywane jest na wyrażeniu debugger. Działa to tak jak ustawienie breakpointu w kodzie źródłowym skryptu.

+ +

Paused at a debugger statement.

+ +

Specyfikacje

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecyfikacjaStatusKomentarz
{{SpecName('ESDraft', '#sec-debugger-statement', 'Debugger statement')}}{{Spec2('ESDraft')}} 
{{SpecName('ES6', '#sec-debugger-statement', 'Debugger statement')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-12.15', 'Debugger statement')}}{{Spec2('ES5.1')}}Wstępna definicja
{{SpecName('ES3', '#sec-7.5.3', 'Debugger statement')}}{{Spec2('ES3')}} 
{{SpecName('ES1', '#sec-7.4.3', 'Debugger statement')}}{{Spec2('ES1')}}Jedynie wspomniane jako zarezerwowane słowo kluczowe
+ +


+ {{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
CechaChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Podstawowe wsparcia{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
CechaAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Podstawowe wsparcie{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Zobacz też

+ + diff --git a/files/pl/web/javascript/reference/statements/do...while/index.html b/files/pl/web/javascript/reference/statements/do...while/index.html new file mode 100644 index 0000000000..a57caf17ee --- /dev/null +++ b/files/pl/web/javascript/reference/statements/do...while/index.html @@ -0,0 +1,54 @@ +--- +title: do...while +slug: Web/JavaScript/Referencje/Polecenia/do...while +tags: + - Dokumentacja_JavaScript + - Dokumentacje + - JavaScript + - Wszystkie_kategorie +translation_of: Web/JavaScript/Reference/Statements/do...while +--- +

+

+

Podsumowanie

+

Wykonuje zadane polecenia dopóki warunek jest spełniony. Polecenia wykonywane są przynajmniej raz. +

+ + + + + + + + + + + + +
Polecenie
Zaimplementowane w:JavaScript 1.2, NES 3.0
Wersja ECMA:ECMA-262, Edycja 3 +
+

Składnia

+
do
+   polecenia
+while (warunek);
+
+

Parametry

+
polecenia 
Blok poleceń, który jest wykonywany przynajmniej raz. i jest wykonywany ponownie tak długo, jak warunek jest spełniony. +
+
warunek 
Obliczany przy każdym przejściu pętli. Jeśli warunek ma wartość prawda, polecenia w bloku go poprzedzającym są wykonywane ponownie. Kiedy warunek osiągnie wartość fałsz, sterowanie przepływa do następnego polecenia po pętli do...while +
+

Przykłady

+

Przykład: Zastosowanie do...while

+

W poniższym przykładzie pętla do...while wykonywana jest przynajmniej raz, a następnie jej wykonywanie jest powtarzane tak długo, aż i będzie większe lub równe 5. +

+
do {
+   i+=1;
+   document.write(i);
+} while (i<5);
+
+


+


+

+
+
+{{ languages( { "en": "en/Core_JavaScript_1.5_Reference/Statements/do...while", "es": "es/Referencia_de_JavaScript_1.5/Sentencias/do...while", "fr": "fr/R\u00e9f\u00e9rence_de_JavaScript_1.5_Core/Instructions/do...while", "ja": "ja/Core_JavaScript_1.5_Reference/Statements/do...while" } ) }} diff --git a/files/pl/web/javascript/reference/statements/empty/index.html b/files/pl/web/javascript/reference/statements/empty/index.html new file mode 100644 index 0000000000..4c55c3f4dd --- /dev/null +++ b/files/pl/web/javascript/reference/statements/empty/index.html @@ -0,0 +1,92 @@ +--- +title: empty +slug: Web/JavaScript/Referencje/Polecenia/Empty +tags: + - JavaScript + - funkcja języka + - wyrażenie +translation_of: Web/JavaScript/Reference/Statements/Empty +--- +
{{jsSidebar("Statements")}}
+ +

Puste wyrażenie jest używane do podania braku wyrażenia tam, gdzie składnia JavaScript wymaga jakiejkolwiek instrukcji.

+ +
{{EmbedInteractiveExample("pages/js/statement-empty.html")}}
+ + + +

Składnia

+ +
;
+
+ +

Opis

+ +

Puste wyrażenie jest zapisywane jako średnik, wskazujący na to, że żadna instrukcja nie będzie wykonana, nawet jeśli składnia JavaScript wymaga jakiejkolwiek operacji.

+ +

Przeciwna zachowanie, kiedy potrzebne jest użycie kilku wyrażeń tam, gdzie JavaScript pozwala tylko na jedno, jest możliwe dzięki blokom instrukcji, które łączą kilka wyrażeń w jedno.

+ +

Przykłady

+ +

Pusta pętla

+ +

Puste wyrażenie jest czasem używane w pętlach. Poniższy przykład prrzedstawia ciało pustej pętli:

+ +
let arr = [1, 2, 3];
+
+// Nadaj wszystkim elementom tablicy wartość 0
+for (let i = 0; i < arr.length; arr[i++] = 0) /* puste wyrażenie */ ;
+
+console.log(arr);
+// [0, 0, 0]
+
+ +

Nieumyślne użycie

+ +

Dobrym pomysłem jest dodanie komentarza do umyślnego użycia pustego wyrażenia, ponieważ nieoczywistym może się okazać rozróżnienie takiej instrukcji od zwykłego średnika.

+ +

W poniższym przykładzie użycie pustego wyrażenia prawdopodobnie nie jest umyślne:

+ +
if (condition);       // Uwaga, ten "if" nic nie robi!
+   killTheUniverse()  // To polecenie będzie zawsze wykonane!!!
+
+ +

W kolejnym przykładzie użyta jest instrukcja warunkowa {{jsxref("Statements/if...else", "if...else")}} bez nawiasów klamrowych ({}).

+ +

Jeśli wartość zmiennej trzy jest równa true, nic się nie stanie, zmienna cztery nie ma znaczenia, również funkcja odpalRakietę w przypadku else nie będzie wykonana.

+ +
if (jeden)
+  wykonajJeden();
+else if (dwa)
+  wykonajDwa();
+else if (trzy)
+  ; // puste wyrażenie
+else if (cztery)
+  wykonajCztery();
+else
+  odpalRakietę();
+ +

Specyfikacje

+ + + + + + + + + + +
Specyfikacja
{{SpecName('ESDraft', '#sec-empty-statement', 'Empty statement')}}
+ +

Wsparcie przeglądarek

+ + + +

{{Compat("javascript.statements.empty")}}

+ +

Zobacz też

+ + diff --git a/files/pl/web/javascript/reference/statements/export/index.html b/files/pl/web/javascript/reference/statements/export/index.html new file mode 100644 index 0000000000..3b29f1987b --- /dev/null +++ b/files/pl/web/javascript/reference/statements/export/index.html @@ -0,0 +1,47 @@ +--- +title: export +slug: Web/JavaScript/Referencje/Polecenia/export +tags: + - Dokumentacja_JavaScript + - Dokumentacje + - JavaScript + - Wszystkie_kategorie +translation_of: Web/JavaScript/Reference/Statements/export +--- +

+

+

Podsumowanie

+

Pozwala podpisanemu skryptowi na dostarczanie własności, funkcji i obiektów do innych podpisanych lub niepodpisanych skryptów. Tej opcji nie ma w 3 edycji ECMA-262. +

+ + + + + + + + +
Instrukcja
Zaimplementowana w:JavaScript 1.2, NES 3.0
+

Składnia

+

+export nazwa1, nazwa2, ..., nazwaN; + +

+export *; + +

+

Parametry

+
nazwaN 
Własność, funkcja, lub obiekt do wyeksportowania. +
+

Opis

+

Zazwyczaj informacja w podpisanym skrypcie jest dostępna tylko dla skryptów podpisanych przez tych samych wykonawców. Poprzez wyeksportowanie własności, funkcji i obiektów podpisany skrypt udostępnia tę informację dla każdego skryptu (podpisanego lub niepodpisanego). Skrypt otrzymujący używa instrukcji import, by uzyskać dostęp do tej informacji. +

Pierwsza składnia eksportuje określone własności, funkcje i obiekty. +

Druga składnia eksportuje wszystkie własności, funkcje i obiekty ze skryptu. +

+

Zobacz także

+

import +


+

+
+
+{{ languages( { "en": "en/Core_JavaScript_1.5_Reference/Statements/export", "fr": "fr/R\u00e9f\u00e9rence_de_JavaScript_1.5_Core/Instructions/export", "ja": "ja/Core_JavaScript_1.5_Reference/Statements/export" } ) }} diff --git a/files/pl/web/javascript/reference/statements/for...in/index.html b/files/pl/web/javascript/reference/statements/for...in/index.html new file mode 100644 index 0000000000..d8c17d3b3e --- /dev/null +++ b/files/pl/web/javascript/reference/statements/for...in/index.html @@ -0,0 +1,173 @@ +--- +title: for...in +slug: Web/JavaScript/Referencje/Polecenia/for...in +tags: + - JavaScript + - wyrażenie +translation_of: Web/JavaScript/Reference/Statements/for...in +--- +
{{jsSidebar("Statements")}}
+ +

Wyrażenie for...in iteruje po nazwach wszystkich wyliczalnych własnościach obiektu, włączając w to odziedziczone wyliczalne właściwości. for...in pomija te właściwości, które są indeksowane Symbolami.

+ +
{{EmbedInteractiveExample("pages/js/statement-forin.html")}}
+ + + +

Składnia

+ +
for (zmienna in obiekt)
+  polecenie
+ +
+
zmienna
+
W każdej iteracji, zmiennej przypisywana jest inna nazwa własności.
+
obiekt
+
Obiekt, po którego niesymbolicznych wyliczalnych własnościach iterujemy.
+
+ +

Opis

+ +

for...in iteruje jedynie po wyliczalnych i jednocześnie niesymbolicznych właściwościach. Obiekty utworzone za pomocą wbudowanych konstruktorów (np. Array czy Object) dziedziczą niewyliczalne właściwości z m.in. Object.protoype oraz String.prototype, takie jak metoda {{jsxref("String.indexOf", "indexOf()")}} ze {{jsxref("String")}} albo {{jsxref("Object.toString", "toString()")}} z {{jsxref("Object")}}. Pętla przejdzie przez wszystkie wyliczalne właściwości – zarówno własne, jak i odziedziczone z prototypu konstruktora.

+ +

Usunięte, dodane lub zmodyfikowane własności

+ +

Pętla for...in iteruje po właściwościach w arbitralnej kolejności (zobacz więcej w opisie operatora {{jsxref("Operators/delete", "delete")}}, dlaczego nie można liczyć na konkretną kolejność właściwości – szczególnie w różnych przeglądarkach).

+ +

Jeśli właściwość zostanie zmodyfikowana w danej iteracji, a dopiero następnie odwiedzona przez for...in, przyjmuje tę późniejszą wartość. Usunięcie właściwości przed jej odwiedzeniem przez pętlę, spowoduje, że nie wystąpi w żadnej z późniejszych iteracji. Natomiast właściwość dodana do obiektu w trakcie iterowania może (ale nie musi) zostać odwiedzona przez pętlę.

+ +

Ogólnie, w trakcie iterowania z użyciem for...in najlepiej jest nie modyfikować innych właściwości obiektu niż ta, która jest aktualnie odwiedzona. Nie ma żadnej gwarancji, że dodana właściwość zostanie odwiedzona, ani że właściwość usuwana zostanie odwiedzona przed skasowaniem. Podobnie, nie ma gwarancji, czy właściwość zmodyfikowana zostanie odwiedzona przed, czy po modyfikacji.

+ +

Iterowanie po tablicy i for...in

+ +
+

Uwaga: wyrażenie for...in nie powinno być używane na obiektach klasy{{jsxref("Array")}}, gdzie kolejność elementów jest ważna.

+
+ +

Indeksy tablic są niczym innym jak właściwościami obiektu – z tym, że ich nazwy są liczbowe, a nie słowne. Dlatego nie ma gwarancji, że for...in odwiedzi je w jakiejkolwiek konkretnej kolejności. Ponadto, pętla zwróci także nieliczbowe właściwości oraz te odziedziczone.

+ +

Kiedy kolejność odwiedzania elementów ma znaczenie, iterowanie po elementach tablicy powinno odbywać się z użyciem pętli {{jsxref("Statements/for", "for")}} (albo {{jsxref("Array.prototype.forEach()")}} albo pętli {{jsxref("Statements/for...of", "for...of")}}), ze względu na to, że kolejność iterowania po właściwościach jest zależna od implementacji.

+ +

Iterowanie jedynie po własnych właściwościach

+ +

Jeżeli potrzebujesz iterować tylko po własnych właściwościach obiektu, użyj {{jsxref("Object.getOwnPropertyNames", "getOwnPropertyNames()")}}, albo sprawdzaj za każdym razem, czy właściwość jest właściwością własną za pomocą {{jsxref("Object.prototype.hasOwnProperty", "hasOwnProperty()")}}({{jsxref("Object.prototype.propertyIsEnumerable", "propertyIsEnumerable()")}} również moży zostać użyte). Alternatywnie, jeśli jesteś pewien, że nie spowoduje to problemów w kodzie, możesz rozszerzyć wbudowane prototypy o metodę sprawdzającą, czy właściwość jest własna.

+ +

Dlaczego używać for...in?

+ +

Skoro pętla for...in została stworzona do iterowania po właściwościach obiektu i nie jest zalecana do pracy z tablicami, to jaki może bć z niej pożytek?

+ +

Najbardziej praktyczna jest w sytuacjach związanych z debugowaniem, zapewniając łatwy sposób na sprawdzenie właściwości obiektu (wypisując je do konsoli lub gdziekolwiek indziej). Oprócz tego, są sytuacje, kiedy pary klucz-wartość są indeksowane innym typem niż liczba. Wtedy po takim "słowniku" można przeiterować za pomocą for...in.

+ +

Przykłady

+ +

Użycie for...in

+ +

Pętla for...in poniżej iteruje po wszystkich wyliczalnych właściwościach obiektu obj i wypisuje je do konsoli.

+ +
var obj = {a: 1, b: 2, c: 3};
+
+for (const prop in obj) {
+  console.log(`obj.${prop} = ${obj[prop]}`);
+}
+
+// Wyjście:
+// "obj.a = 1"
+// "obj.b = 2"
+// "obj.c = 3"
+ +

Iterowanie po własnych właściwościach

+ +

Następny przykład pokazuje użycie {{jsxref("Object.prototype.hasOwnProperty", "hasOwnProperty()")}}, aby nie wyświetlać właściwości odziedziczonych przez ColoredTriangle.

+ +
var triangle = {a: 1, b: 2, c: 3};
+
+function ColoredTriangle() {
+  this.color = 'red';
+}
+
+ColoredTriangle.prototype = triangle;
+
+var obj = new ColoredTriangle();
+
+for (const prop in obj) {
+  if (obj.hasOwnProperty(prop)) {
+    console.log(`obj.${prop} = ${obj[prop]}`);
+  }
+}
+
+// Wyjście:
+// "obj.color = red"
+
+ +

Specyfikacje

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecyfikacjaStatusKomentarz
{{SpecName('ESDraft', '#sec-for-in-and-for-of-statements', 'for...in statement')}}{{Spec2('ESDraft')}}
{{SpecName('ES6', '#sec-for-in-and-for-of-statements', 'for...in statement')}}{{Spec2('ES6')}}
{{SpecName('ES5.1', '#sec-12.6.4', 'for...in statement')}}{{Spec2('ES5.1')}}
{{SpecName('ES3', '#sec-12.6.4', 'for...in statement')}}{{Spec2('ES3')}}
{{SpecName('ES1', '#sec-12.6.3', 'for...in statement')}}{{Spec2('ES1')}}Definicja początkowa.
+ +

Zgodność z przeglądarkami

+ + + +

{{Compat("javascript.statements.for_in")}}

+ +

Zgodność: Wyrażenie incjalizujące w trybie ścisłym

+ +

Przed Firefoksem 40, było możliwe używanie wyrażenia incjalizującego (i=0) w pętli for...in:

+ +
var obj = {a: 1, b: 2, c: 3};
+for (var i = 0 in obj) {
+  console.log(obj[i]);
+}
+// 1
+// 2
+// 3
+
+ +

To niestandardowe zachowanie jest ignorowane począwszy od wersji 40 i powoduje zgłoszenie błędu {{jsxref("SyntaxError")}} ("for-in loop head declarations may not have initializers") w trybie ścisłym ({{bug(748550)}} i {{bug(1164741)}}).

+ +

Inne silniki, takie jak v8 (Chrome), Chakra (IE/Edge), i JSC (WebKit/Safari) również mogą przestać obsługiwać taką konstrukcję.

+ +

Zobacz też

+ + diff --git a/files/pl/web/javascript/reference/statements/for/index.html b/files/pl/web/javascript/reference/statements/for/index.html new file mode 100644 index 0000000000..1178c277ef --- /dev/null +++ b/files/pl/web/javascript/reference/statements/for/index.html @@ -0,0 +1,58 @@ +--- +title: for +slug: Web/JavaScript/Referencje/Polecenia/for +tags: + - Dokumentacja_JavaScript + - Dokumentacje + - JavaScript + - Wszystkie_kategorie +translation_of: Web/JavaScript/Reference/Statements/for +--- +

+

+

Podsumowanie

+

Tworzy pętlę, która składa się z trzech opcjonalnych wyrażeń, załączonych w nawiasach i oddzielonych średnikami, po których występuje instrukcja wykonywana w pętli. +

+ + + + + + + + + + + + +
Instrukcja
Zaimplementowana w:JavaScript 1.0, NES 2.0
Wersja ECMA:ECMA-262
+

Składnia

+
for ([wyrażenie-wstępne]; [warunek]; [wyrażenie-inkrementacji])
+   instrukcja
+
+

Parametry

+
wyrażenie-wstępne 
Wyrażenie (włącznie z wyrażeniami przypisania) lub deklaracja zmiennej. Zazwyczaj używane do zainicjalizowania zmiennej licznika. Wyrażenie to może opcjonalnie deklarować nowe zmienne za pomocą słowa kluczowego var. Zmienne te nie są lokalne dla pętli, inaczej mówiąc, mają one taki sam zasięg jak pętla for. +
+
warunek 
Wyrażenie sprawdzane podczas każdego przejścia przez pętlę. Jeśli warunek jest prawdziwy, wykonywana jest instrukcja. Sprawdzenie warunku jest opcjonalne. Jeśli zostanie pominięte, warunek jest zawsze uznawany jako prawdziwy.
+
wyrażenie-inkrementacji 
Ogólnie używane do aktualizacji lub inkrementacji wartości zmiennej licznika. +
+
instrukcja 
Instrukcja, wykonywana dopóki warunek oceniany jest jako prawdziwy. Aby wykonać większą ilość instrukcji wewnątrz pętli, użyj instrukcji block ({ ... }), aby pogrupować te instrukcje. +
+

Przykład

+

Przykład: Zastosowanie for

+

Następująca instrukcja for rozpoczyna się deklaracją zmiennej i oraz zainicjalizowaniem jej wartości początkowej 0. Instrukcja sprawdza kolejno czy wartość zmiennej i jest mniejsza od dziewięciu, wykonuje dwie następujące po sobie instrukcje oraz zwiększa o 1 wartość zmiennej i podczas każdego kolejnego przejścia przez pętlę. +

+
for (var i = 0; i < 9; i++) {
+   n += i;
+   myfunc(n);
+}
+
+

Zobacz także

+

while, +do...while +


+


+

+
+
+{{ languages( { "en": "en/Core_JavaScript_1.5_Reference/Statements/for", "es": "es/Referencia_de_JavaScript_1.5/Sentencias/for", "fr": "fr/R\u00e9f\u00e9rence_de_JavaScript_1.5_Core/Instructions/for", "ja": "ja/Core_JavaScript_1.5_Reference/Statements/for" } ) }} diff --git a/files/pl/web/javascript/reference/statements/function/index.html b/files/pl/web/javascript/reference/statements/function/index.html new file mode 100644 index 0000000000..6b9eba95dd --- /dev/null +++ b/files/pl/web/javascript/reference/statements/function/index.html @@ -0,0 +1,68 @@ +--- +title: function +slug: Web/JavaScript/Referencje/Polecenia/function +tags: + - Dokumentacja_JavaScript + - Dokumentacje + - JavaScript + - Wszystkie_kategorie +translation_of: Web/JavaScript/Reference/Statements/function +--- +

+

+

Podsumowanie

+

Deklaruje funkcję z określonymi parametrami. +

Możesz również zdefiniować funkcję używając konstruktora Function oraz operator function (wyrażenie funkcji). +

+ + + + + + + + + + + + +
Instrukcja
Zaimplementowana w:JavaScript 1.0, NES 2.0 +

JavaScript 1.5, NES 6.0: Dodano deklaracje funkcji warunkowych (rozszerzenie Netscape). +

+
Wersja ECMA:ECMA-262 +
+

Składnia

+
function nazwa([argument] [, argument] [..., argument]) {
+   instrukcje
+}
+
+

Parametry

+
nazwa 
Nazwa funkcji. +
+
argument 
Nazwa argumentu, który ma zostać przekazany do funkcji. Funkcja może posiadać do 255 argumentów. +
+
instrukcje 
Instrukcje, które stanowią ciało funkcji. +
+

Opis

+

Aby zwrócić wartość, funkcja musi zawierać instrukcję return określającą wartość, która ma zostać zwrócona. +

Funkcja utworzona za pomocą instrukcji function jest obiektem Function i posiada wszystkie własności, metody i zachowania obiektów Function. Zobacz Function, aby uzyskać szczegółowe informacje o funkcjach. +

Funkcja może zostać zadeklarowana również wewnątrz wyrażenia. W takim przypadku funkcja jest zazwyczaj anonimowa. Zobacz operator function, aby uzyskać więcej informacji o function (wyrażenie funkcji). +

Funkcje mogą być deklarowane warunkowo. To znaczy, definicja funkcji może zostać zagnieżdżona wewnątrz instrukcji if. Technicznie rzecz biorąc, takie deklaracje nie są właściwie deklaracjami funkcji; są one wyrażeniami funkcji. +

+

Przykłady

+

Przykład: Zastosowanie function

+

Poniższy kod deklaruje funkcję, która zwraca całkowitą kwotę sprzedaży, gdy podano liczbę sprzedanych produktów a, b i c. +

+
function calc_sales(units_a, units_b, units_c) {
+   return units_a*79 + units_b * 129 + units_c * 699;
+}
+
+

Zobacz także

+

Funkcje, +Function, +function operator +


+

+
+
+{{ languages( { "en": "en/Core_JavaScript_1.5_Reference/Statements/function", "es": "es/Referencia_de_JavaScript_1.5/Sentencias/function", "fr": "fr/R\u00e9f\u00e9rence_de_JavaScript_1.5_Core/Instructions/function", "ja": "ja/Core_JavaScript_1.5_Reference/Statements/function" } ) }} diff --git a/files/pl/web/javascript/reference/statements/function_star_/index.html b/files/pl/web/javascript/reference/statements/function_star_/index.html new file mode 100644 index 0000000000..5962e0c286 --- /dev/null +++ b/files/pl/web/javascript/reference/statements/function_star_/index.html @@ -0,0 +1,309 @@ +--- +title: function* +slug: Web/JavaScript/Referencje/Polecenia/function* +translation_of: Web/JavaScript/Reference/Statements/function* +--- +
{{jsSidebar("Statements")}}
+ +

Deklaracja function*  (Słowo kluczowe function przed gwiazdką) definiuje funkcję generatora, która zwraca obiekt {{jsxref("Obiekty/Generator","Generator")}}.

+ +
+

Możesz także zdefinować funkcje generatora używając konstruktora {{jsxref("GeneratorFunction")}} oraz {{jsxref("Operators/function*", "function* expression")}}.

+
+ +

Składnia

+ +
function* name([param[, param[, ... param]]]) {
+   statements
+}
+
+ +
+
name
+
Nazwa funkcji.
+
+ +
+
param
+
Nazwa argumentu przekazywanego do funkcji. Funkcja może posiadać maksymalnie 255 argumentów.
+
+ +
+
statements
+
Polecenia wypełniające ciało funkcji.
+
+ +

Opis

+ +

Generatory są specyficznym rodzajem funkcji, która może być zatrzymywana i wznawiana. Pomiędzy kolejnymi wznowieniami zachowany jest kontekst (variable bindings).

+ +

Wywołanie funkcji generatora nie wykonuje poleceń w niej zawartych od razu; Zamiast tego, zwracany jest obiekt iteratora. Dopiero kiedy na iteratorze wywoływana jest metoda next() wykonywane jest ciało funkcji, do momentu wystąpienia pierwszego wyrażenia {{jsxref("Operators/yield", "yield")}}. {{jsxref("Operators/yield", "yield")}} Określa jaka wartość zostanie zwrócona z generatora lub, jeśli użyto {{jsxref("Operators/yield*", "yield*")}}, wskazuje na kolejny do wywołania generator. Metoda next() zwraca obiekt z właściwością value zawierającą zwróconą przez {{jsxref("Operators/yield", "yield")}} wartość oraz właściowść done , która wskazuje czy generator zwórcił już wartość ostatniego {{jsxref("Operators/yield", "yield")}}. Wywołanie metody next() z argumentem, będzie wznawiało wykonywanie generatora za miejscem gdzie występował {{jsxref("Operators/yield", "yield")}} wstrzymujący generator.

+ +

Przykłady

+ +

Prosty przykład

+ +
function* idMaker() {
+  var index = 0;
+  while (index < 3)
+    yield index++;
+}
+
+var gen = idMaker();
+
+console.log(gen.next().value); // 0
+console.log(gen.next().value); // 1
+console.log(gen.next().value); // 2
+console.log(gen.next().value); // undefined
+// ...
+ +

Przykład z yield*

+ +
function* anotherGenerator(i) {
+  yield i + 1;
+  yield i + 2;
+  yield i + 3;
+}
+
+function* generator(i) {
+  yield i;
+  yield* anotherGenerator(i);
+  yield i + 10;
+}
+
+var gen = generator(10);
+
+console.log(gen.next().value); // 10
+console.log(gen.next().value); // 11
+console.log(gen.next().value); // 12
+console.log(gen.next().value); // 13
+console.log(gen.next().value); // 20
+
+ +

Przekazywanie parametrów do generatora

+ +
function* logGenerator() {
+  console.log(yield);
+  console.log(yield);
+  console.log(yield);
+}
+
+var gen = logGenerator();
+
+// the first call of next executes from the start of the function
+// until the first yield statement
+gen.next();
+gen.next('pretzel'); // pretzel
+gen.next('california'); // california
+gen.next('mayonnaise'); // mayonnaise
+
+ +

Wyrażenie return wewnątrz generatora

+ +
function* yieldAndReturn() {
+  yield "Y";
+  return "R";
+  yield "unreachable";
+}
+
+var gen = yieldAndReturn()
+console.log(gen.next()); // { value: "Y", done: false }
+console.log(gen.next()); // { value: "R", done: true }
+console.log(gen.next()); // { value: undefined, done: true }
+ +

Generator nie jest typowym konstruktorem

+ +
function* f() {}
+var obj = new f; // throws "TypeError: f is not a constructor"
+ +

Specyfikacja

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#', 'function*')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ES2016', '#', 'function*')}}{{Spec2('ES2016')}}Changed that generators should not have [[Construct]] trap and will throw when used with new.
{{SpecName('ESDraft', '#', 'function*')}}{{Spec2('ESDraft')}} 
+ +

Kompatybilność przeglądarek

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet Explorer EdgeOperaSafari (WebKit)
Basic support{{CompatChrome(39.0)}}{{CompatGeckoDesktop("26.0")}}{{CompatNo}}1326{{CompatSafari("10")}}
yield*{{CompatVersionUnknown}}{{CompatGeckoDesktop("27.0")}}{{CompatNo}}1326{{CompatSafari("10")}}
IteratorResult object instead of throwing{{CompatVersionUnknown}}{{CompatGeckoDesktop("29.0")}}{{CompatNo}}13{{CompatVersionUnknown}}{{CompatUnknown}}
Not constructable with new as per ES2016{{CompatVersionUnknown}}{{CompatGeckoDesktop("43.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Trailing comma in parameters{{CompatUnknown}}{{CompatGeckoDesktop("52.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatVersionUnknown}}{{CompatGeckoMobile("26.0")}}{{CompatNo}}{{CompatNo}}{{CompatSafari("10")}}{{CompatChrome(39.0)}}
yield*{{CompatNo}}{{CompatVersionUnknown}}{{CompatGeckoMobile("27.0")}}{{CompatNo}}{{CompatNo}}{{CompatSafari("10")}}{{CompatVersionUnknown}}
IteratorResult object instead of throwing{{CompatNo}}{{CompatUnknown}}{{CompatGeckoMobile("29.0")}}{{CompatNo}}{{CompatNo}}{{CompatUnknown}}{{CompatVersionUnknown}}
Not constructable with new as per ES2016{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("43.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Trailing comma in parameters{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("52.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

Firefox-specific notes

+ +

Generatory i iteratory w Firefox przed wersją 26

+ +

Starsze wersje Firefox implementują nieco inną, bardziej archaiczną propozycje specyfikacji. W starszych wersjach definiowanie generatorów odbywało się za pomocą wyłącznie słowa kluczowego function (bez dodatkowej gwiazdki). Tą i wiele innych drobnych różnic można sprawdzić na Legacy generator function.

+ +

IteratorResult zwraca obiekt zamiast rzucać wyjątek

+ +

Począwszy od silnika Gecko 29 {{geckoRelease(29)}}, zakończony generator nie rzuca już więcej wyjątkami {{jsxref("TypeError")}} "generator has already finished". W zamian za to zwraca obiekt IteratorResult w postaci { value: undefined, done: true } ({{bug(958951)}}).

+ +

Zobacz także

+ + diff --git a/files/pl/web/javascript/reference/statements/if...else/index.html b/files/pl/web/javascript/reference/statements/if...else/index.html new file mode 100644 index 0000000000..38dd3c8f8a --- /dev/null +++ b/files/pl/web/javascript/reference/statements/if...else/index.html @@ -0,0 +1,65 @@ +--- +title: if...else +slug: Web/JavaScript/Referencje/Polecenia/if...else +tags: + - Dokumentacja_JavaScript + - Dokumentacje + - JavaScript + - Wszystkie_kategorie +translation_of: Web/JavaScript/Reference/Statements/if...else +--- +

+

+

Podsumowanie

+

Wykonuje blok poleceń, jeśli dany warunek jest spełniony. Jeśli warunek nie jest spełniony, może zostać wykonany inny blok poleceń. +

+ + + + + + + + + + + + +
Polecenie
Zaimplementowane w:JavaScript 1.0, NES 2.0
Wersja ECMA:ECMA-262
+

Składnia

+
if (warunek) {
+   polecenia1
+}
+[else {
+   polecenia2
+}]
+
+

Parametry

+
warunek 
może być dowolnym wyrażeniem JavaScriptu przyjmującym wartości logiczne (true, false) lub mogącym być na wartości logiczne przekonwertowane. Warunek musi być ujęty w nawiasach. Jeśli warunek jest spełniony (ma wartość true), wykonywane są polecenia w bloku polecenia1. +
+
polecenia1, polecenia2 
mogą być dowolnymi poleceniami JavaScriptu, w tym zagnieżdżonymi poleceniami if...else. Bloki wielu poleceń muszą być ujęte w nawiasy klamrowe. +
+

Opis

+

Nie powinno się używać prostych operatorów przypisania w wyrażeniu warunkowym. Przykładowo, nie należy używać kodu podobnego do poniższego: +

+
if(x = y)
+{
+   /* zrób coś */
+}
+
+

Jeśli potrzebujesz użyć przypisania w wyrażeniu warunkowym, użyj dodatkowej pary nawiasów. Na przykład: if( (x = y) ). +

+

Przykłady

+

Przykład: Zastosowanie if...else

+
if (cipher_char == from_char) {
+   result = result + to_char
+   x++}
+else
+   result = result + clear_char
+
+


+


+

+
+
+{{ languages( { "en": "en/Core_JavaScript_1.5_Reference/Statements/if...else", "es": "es/Referencia_de_JavaScript_1.5/Sentencias/if...else", "fr": "fr/R\u00e9f\u00e9rence_de_JavaScript_1.5_Core/Instructions/if...else", "ja": "ja/Core_JavaScript_1.5_Reference/Statements/if...else" } ) }} diff --git a/files/pl/web/javascript/reference/statements/import/index.html b/files/pl/web/javascript/reference/statements/import/index.html new file mode 100644 index 0000000000..406050c420 --- /dev/null +++ b/files/pl/web/javascript/reference/statements/import/index.html @@ -0,0 +1,55 @@ +--- +title: import +slug: Web/JavaScript/Referencje/Polecenia/import +tags: + - Dokumentacja_JavaScript + - Dokumentacje + - JavaScript + - Wszystkie_kategorie +translation_of: Web/JavaScript/Reference/Statements/import +--- +

+

+

Podsumowanie

+

Pozwala zaimportować własności, funkcje i obiekty z podpisanego skryptu, który wyeksportował informację. +

Tej cechy nie ma w 3 edycji ECMA 262. +

+ + + + + + + + +
Instrukcja
Zaimplementowane w:JavaScript 1.2, NES 3.0
+

Składnia

+

+import objectName.name1, objectName.name2, ..., objectName.nameN; + +

+import objectName.*; + +

+

Parametry

+
objectName 
Nazwa obiektu, który przyjmie zaimportowane nazwy. +
+
nameN 
Własność, funkcja lub obiekt do zaimportowania. +
+

Opis

+

Parametr objectName jest nazwą obiektu, który przyjmie zaimportowane nazwy. Na przykład jeśli f i p zostały wyeksportowane i obj jest obiektem z importującego skryptu, to poniższy kod zrobi f i p dostępnymi jako własności obj wewnątrz skryptu importującego. +

+
import obj.f, obj.p;
+
+

Pierwsza składnia importuje określone własności, funkcje i obiekty z wyeksportowanego skryptu. +

Druga składnia importuje wszystkie własności, funkcje i obiekty z wyeksportowanego skryptu. +

Zazwyczaj informacja w podpisanym skrypcie jest dostępna tylko dla skryptów podpisanych przez tych samych wykonawców. Poprzez wyeksportowanie (używając instrukcji export) własności, funkcji i obiektów podpisany skrypt robi tę informację dostępną dla każdego skryptu (podpisanego lub niepodpisanego). Skrypt otrzymujący używa instrukcji import, by uzyskać dostęp do tej informacji. +

Skrypt musi załadować skrypt eksportowy do okna, ramki lub warstwy zanim będzie on mógł zaimportować i użyć którejkolwiek z wyeksportowanych własności, funkcji lub obiektów. +

+

Zobacz także

+

export +


+

+
+
+{{ languages( { "en": "en/Core_JavaScript_1.5_Reference/Statements/import", "fr": "fr/R\u00e9f\u00e9rence_de_JavaScript_1.5_Core/Instructions/import", "ja": "ja/Core_JavaScript_1.5_Reference/Statements/import" } ) }} diff --git a/files/pl/web/javascript/reference/statements/index.html b/files/pl/web/javascript/reference/statements/index.html new file mode 100644 index 0000000000..b6f58b783c --- /dev/null +++ b/files/pl/web/javascript/reference/statements/index.html @@ -0,0 +1,149 @@ +--- +title: Polecenia +slug: Web/JavaScript/Referencje/Polecenia +tags: + - Dokumentacja_JavaScript + - Dokumentacje + - JavaScript + - Strony_wymagające_dopracowania + - Wszystkie_kategorie +translation_of: Web/JavaScript/Reference/Statements +--- +
{{jsSidebar("Statements")}}
+ +

JavaScript applications consist of statements with an appropriate syntax. A single statement may span multiple lines. Multiple statements may occur on a single line if each statement is separated by a semicolon. This isn't a keyword, but a group of keywords.

+ +

Statements and declarations by category

+ +

For an alphabetical listing see the sidebar on the left.

+ +

Control flow

+ +
+
{{jsxref("Statements/block", "Block")}}
+
A block statement is used to group zero or more statements. The block is delimited by a pair of curly brackets.
+
{{jsxref("Statements/break", "break")}}
+
Terminates the current loop, switch, or label statement and transfers program control to the statement following the terminated statement.
+
{{jsxref("Statements/continue", "continue")}}
+
Terminates execution of the statements in the current iteration of the current or labeled loop, and continues execution of the loop with the next iteration.
+
{{jsxref("Statements/Empty", "Empty")}}
+
An empty statement is used to provide no statement, although the JavaScript syntax would expect one.
+
{{jsxref("Statements/if...else", "if...else")}}
+
Executes a statement if a specified condition is true. If the condition is false, another statement can be executed.
+
{{jsxref("Statements/switch", "switch")}}
+
Evaluates an expression, matching the expression's value to a case clause, and executes statements associated with that case.
+
{{jsxref("Statements/throw", "throw")}}
+
Throws a user-defined exception.
+
{{jsxref("Statements/try...catch", "try...catch")}}
+
Marks a block of statements to try, and specifies a response, should an exception be thrown.
+
+ +

Declarations

+ +
+
{{jsxref("Statements/var", "var")}}
+
Declares a variable, optionally initializing it to a value.
+
{{jsxref("Statements/let", "let")}}
+
Declares a block scope local variable, optionally initializing it to a value.
+
{{jsxref("Statements/const", "const")}}
+
Declares a read-only named constant.
+
+ +

Functions and classes

+ +
+
{{jsxref("Statements/function", "function")}}
+
Declares a function with the specified parameters.
+
{{jsxref("Statements/function*", "function*")}}
+
Generator Functions enable writing iterators more easily.
+
{{jsxref("Statements/async_function", "async function")}}
+
Declares an async function with the specified parameters.
+
{{jsxref("Statements/return", "return")}}
+
Specifies the value to be returned by a function.
+
{{jsxref("Statements/class", "class")}}
+
Declares a class.
+
+ +

Iterations

+ +
+
{{jsxref("Statements/do...while", "do...while")}}
+
Creates a loop that executes a specified statement until the test condition evaluates to false. The condition is evaluated after executing the statement, resulting in the specified statement executing at least once.
+
{{jsxref("Statements/for", "for")}}
+
Creates a loop that consists of three optional expressions, enclosed in parentheses and separated by semicolons, followed by a statement executed in the loop.
+
{{deprecated_inline}} {{non-standard_inline()}} {{jsxref("Statements/for_each...in", "for each...in")}}
+
Iterates a specified variable over all values of object's properties. For each distinct property, a specified statement is executed.
+
{{jsxref("Statements/for...in", "for...in")}}
+
Iterates over the enumerable properties of an object, in arbitrary order. For each distinct property, statements can be executed.
+
{{jsxref("Statements/for...of", "for...of")}}
+
Iterates over iterable objects (including {{jsxref("Global_Objects/Array","arrays","","true")}}, array-like objects, iterators and generators), invoking a custom iteration hook with statements to be executed for the value of each distinct property.
+
{{jsxref("Statements/while", "while")}}
+
Creates a loop that executes a specified statement as long as the test condition evaluates to true. The condition is evaluated before executing the statement.
+
+ +

Others

+ +
+
{{jsxref("Statements/debugger", "debugger")}}
+
Invokes any available debugging functionality. If no debugging functionality is available, this statement has no effect.
+
{{jsxref("Statements/export", "export")}}
+
Used to export functions to make them available for imports in external modules, another scripts.
+
{{jsxref("Statements/import", "import")}}
+
Used to import functions exported from an external module, another script.
+
{{jsxref("Statements/label", "label")}}
+
Provides a statement with an identifier that you can refer to using a break or continue statement.
+
+ +
+
{{deprecated_inline}} {{jsxref("Statements/with", "with")}}
+
Extends the scope chain for a statement.
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1', '#sec-12', 'Statements')}}{{Spec2('ES1')}}Initial definition
{{SpecName('ES3', '#sec-12', 'Statements')}}{{Spec2('ES3')}} 
{{SpecName('ES5.1', '#sec-12', 'Statements')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-ecmascript-language-statements-and-declarations', 'ECMAScript Language: Statements and Declarations')}}{{Spec2('ES6')}}New: function*, let, for...of, yield, class
{{SpecName('ESDraft', '#sec-ecmascript-language-statements-and-declarations', 'ECMAScript Language: Statements and Declarations')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ + + +

{{Compat("javascript.statements")}}

+ +

See also

+ + diff --git a/files/pl/web/javascript/reference/statements/label/index.html b/files/pl/web/javascript/reference/statements/label/index.html new file mode 100644 index 0000000000..7ff42b3940 --- /dev/null +++ b/files/pl/web/javascript/reference/statements/label/index.html @@ -0,0 +1,51 @@ +--- +title: etykieta +slug: Web/JavaScript/Referencje/Polecenia/etykieta +tags: + - Dokumentacja_JavaScript + - Dokumentacje + - JavaScript + - Wszystkie_kategorie +translation_of: Web/JavaScript/Reference/Statements/label +--- +

+

+

Podsumowanie

+

Pozwala na oznaczenie punktu w kodzie, do którego będzie można przejść za pomocą poleceń break lub continue. +

Przykładowo, można zastosować etykietę do oznaczenia pętli, a następnie użyć poleceń break lub continue, by zaznaczyć, czy program powinien przerwać pętlę czy kontynuować jej wykonywanie. +

+ + + + + + + + + + + + +
Polecenie
Zaimplementowane w:JavaScript 1.2, NES 3.0
Wersja ECMA:ECMA-262, Edycja 3
+

Składnia

+
etykieta :
+   polecenie
+
+

Parametry

+
etykieta 
Dowolny identyfikator języka JavaScript, który nie jest słowem zarezerwowanym. +
+
polecenie 
Polecenia. Polecenie break może być użyte z dowolnym poleceniem oznaczonym etykietą, a continue można użyć z zapętlonymi poleceniami oznaczonymi etykietami. +
+

Przykłady

+

Przykład użycia etykiety z poleceniem break +znajduje się w rodziale break. Przykład użycia etykiety z poleceniem continue znajduje się w rozdziale continue. +

+

Zobacz także

+

break, +continue +


+


+

+
+
+{{ languages( { "en": "en/Core_JavaScript_1.5_Reference/Statements/label", "es": "es/Referencia_de_JavaScript_1.5/Sentencias/label", "fr": "fr/R\u00e9f\u00e9rence_de_JavaScript_1.5_Core/Instructions/label", "ja": "ja/Core_JavaScript_1.5_Reference/Statements/label" } ) }} diff --git a/files/pl/web/javascript/reference/statements/return/index.html b/files/pl/web/javascript/reference/statements/return/index.html new file mode 100644 index 0000000000..ed7849ed65 --- /dev/null +++ b/files/pl/web/javascript/reference/statements/return/index.html @@ -0,0 +1,48 @@ +--- +title: return +slug: Web/JavaScript/Referencje/Polecenia/return +tags: + - JavaScript + - Wszystkie_kategorie +translation_of: Web/JavaScript/Reference/Statements/return +--- +

+

+

Podsumowanie

+

Określa wartość, która ma być zwrócona przez funkcję. +

+ + + + + + + + + + + + +
Polecenie
Zaimplementowane w:JavaScript 1.0, NES 2.0
Wersja ECMA:ECMA-262
+

Składnia

+

+return wyrażenie; + +

+

Parametry

+
wyrażenie 
wyrażenie, którego wynik ma być zwrócony. +
+

Przykłady

+

Przykład: Zastosowanie return

+

Poniższa funkcja zwraca kwadrat swojego argumentu x (gdzie x jest liczbą). +

+
function kwadrat(x) {
+   return x * x;
+}
+
+


+


+

+
+
+{{ languages( { "en": "en/Core_JavaScript_1.5_Reference/Statements/return", "es": "es/Referencia_de_JavaScript_1.5/Sentencias/return", "fr": "fr/R\u00e9f\u00e9rence_de_JavaScript_1.5_Core/Instructions/return", "ja": "ja/Core_JavaScript_1.5_Reference/Statements/return" } ) }} diff --git a/files/pl/web/javascript/reference/statements/switch/index.html b/files/pl/web/javascript/reference/statements/switch/index.html new file mode 100644 index 0000000000..d131e042ca --- /dev/null +++ b/files/pl/web/javascript/reference/statements/switch/index.html @@ -0,0 +1,285 @@ +--- +title: switch +slug: Web/JavaScript/Referencje/Polecenia/switch +tags: + - Dokumentacja_JavaScript + - Dokumentacje + - JavaScript + - Strony_wymagające_dopracowania + - Wszystkie_kategorie +translation_of: Web/JavaScript/Reference/Statements/switch +--- +
{{jsSidebar("Statements")}}
+ +

Instrukcja switch ocenia wyrażenie, dopasowując wartość wyrażenia do klauzuli case, i wykonuje instrukcje powiązane z tym case, a także instrukcje w przypadkach następujących po dopasowanym przypadku.

+ +
{{EmbedInteractiveExample("pages/js/statement-switch.html")}}
+ + + +

Syntax

+ +
switch (expression) {
+  case value1:
+    //Statements executed when the
+    //result of expression matches value1
+    [break;]
+  case value2:
+    //Statements executed when the
+    //result of expression matches value2
+    [break;]
+  ...
+  case valueN:
+    //Statements executed when the
+    //result of expression matches valueN
+    [break;]
+  [default:
+    //Statements executed when none of
+    //the values match the value of the expression
+    [break;]]
+}
+ +
+
expression
+
Wyrażenie, którego wynik jest dopasowany do każdej klauzuli przypadku.
+
case valueN {{optional_inline}}
+
Klauzula przypadku używana do dopasowania do wyrażenia. Jeśli wyrażenie pasuje do podanej wartościN, instrukcje wewnątrz klauzuli case są wykonywane do końca instrukcji switch lub break.
+
default {{optional_inline}}
+
A default clause; if provided, this clause is executed if the value of expression doesn't match any of the case clauses.
+
+ +

Description

+ +

A switch statement first evaluates its expression. It then looks for the first case clause whose expression evaluates to the same value as the result of the input expression (using the strict comparison, ===) and transfers control to that clause, executing the associated statements. (If multiple cases match the provided value, the first case that matches is selected, even if the cases are not equal to each other.)

+ +

If no matching case clause is found, the program looks for the optional default clause, and if found, transfers control to that clause, executing the associated statements. If no default clause is found, the program continues execution at the statement following the end of switch. By convention, the default clause is the last clause, but it does not need to be so.

+ +

The optional break statement associated with each case label ensures that the program breaks out of switch once the matched statement is executed and continues execution at the statement following switch. If break is omitted, the program continues execution at the next statement in the switch statement.

+ +

Examples

+ +

Using switch

+ +

In the following example, if expr evaluates to "Bananas", the program matches the value with case "Bananas" and executes the associated statement. When break is encountered, the program breaks out of switch and executes the statement following switch. If break were omitted, the statement for case "Cherries" would also be executed.

+ +
switch (expr) {
+  case 'Oranges':
+    console.log('Oranges are $0.59 a pound.');
+    break;
+  case 'Apples':
+    console.log('Apples are $0.32 a pound.');
+    break;
+  case 'Bananas':
+    console.log('Bananas are $0.48 a pound.');
+    break;
+  case 'Cherries':
+    console.log('Cherries are $3.00 a pound.');
+    break;
+  case 'Mangoes':
+  case 'Papayas':
+    console.log('Mangoes and papayas are $2.79 a pound.');
+    break;
+  default:
+    console.log('Sorry, we are out of ' + expr + '.');
+}
+
+console.log("Is there anything else you'd like?");
+
+ +

What happens if I forgot a break?

+ +

If you forget a break then the script will run from the case where the criterion is met and will run the case after that regardless if criterion was met. See example here:

+ +
var foo = 0;
+switch (foo) {
+  case -1:
+    console.log('negative 1');
+    break;
+  case 0: // foo is 0 so criteria met here so this block will run
+    console.log(0);
+    // NOTE: the forgotten break would have been here
+  case 1: // no break statement in 'case 0:' so this case will run as well
+    console.log(1);
+    break; // it encounters this break so will not continue into 'case 2:'
+  case 2:
+    console.log(2);
+    break;
+  default:
+    console.log('default');
+}
+ +

Can I put a default between cases?

+ +

Yes, you can! JavaScript will drop you back to the default if it can't find a match:

+ +
var foo = 5;
+switch (foo) {
+  case 2:
+    console.log(2);
+    break; // it encounters this break so will not continue into 'default:'
+  default:
+    console.log('default')
+    // fall-through
+  case 1:
+    console.log('1');
+}
+
+ +

It also works when you put default before all other cases.

+ +

Rewriting multiple If statements with Switch

+ +

Shown below as a possibility.

+ +
var a = 100;
+var b = NaN;
+switch (true) {
+  case isNaN(a) || isNaN(b):
+    console.log('NaNNaN');
+    break;
+  case a === b:
+    console.log(0);
+    break;
+  case a < b:
+    console.log(-1);
+    break;
+  default:
+    console.log(1);
+}
+
+ +

Methods for multi-criteria case

+ +

Source for this technique is here:

+ +

Switch statement multiple cases in JavaScript (Stack Overflow)

+ +

Multi-case - single operation

+ +

This method takes advantage of the fact that if there is no break below a case statement it will continue to execute the next case statement regardless if the case meets the criteria. See the section titled "What happens if I forgot a break?"

+ +

This is an example of a single operation sequential switch statement, where four different values perform exactly the same.

+ +
var Animal = 'Giraffe';
+switch (Animal) {
+  case 'Cow':
+  case 'Giraffe':
+  case 'Dog':
+  case 'Pig':
+    console.log('This animal will go on Noah\'s Ark.');
+    break;
+  case 'Dinosaur':
+  default:
+    console.log('This animal will not.');
+}
+ +

Multi-case - chained operations

+ +

This is an example of a multiple-operation sequential switch statement, where, depending on the provided integer, you can receive different output. This shows you that it will traverse in the order that you put the case statements, and it does not have to be numerically sequential. In JavaScript, you can even mix in definitions of strings into these case statements as well.

+ +
var foo = 1;
+var output = 'Output: ';
+switch (foo) {
+  case 10:
+    output += 'So ';
+  case 1:
+    output += 'What ';
+    output += 'Is ';
+  case 2:
+    output += 'Your ';
+  case 3:
+    output += 'Name';
+  case 4:
+    output += '?';
+    console.log(output);
+    break;
+  case 5:
+    output += '!';
+    console.log(output);
+    break;
+  default:
+    console.log('Please pick a number from 0 to 6!');
+}
+ +

The output from this example:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ValueLog text
foo is NaN or not 1, 2, 3, 4, 5 or 10Please pick a number from 0 to 6!
10Output: So What Is Your Name?
1Output: What Is Your Name?
2Output: Your Name?
3Output: Name?
4Output: ?
5Output: !
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.2
{{SpecName('ES5.1', '#sec-12.11', 'switch statement')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-switch-statement', 'switch statement')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-switch-statement', 'switch statement')}}{{Spec2('ESDraft')}}
+ +

Browser compatibility

+ + + +

{{Compat("javascript.statements.switch")}}

+ +

See also

+ + diff --git a/files/pl/web/javascript/reference/statements/throw/index.html b/files/pl/web/javascript/reference/statements/throw/index.html new file mode 100644 index 0000000000..a8d57064f5 --- /dev/null +++ b/files/pl/web/javascript/reference/statements/throw/index.html @@ -0,0 +1,197 @@ +--- +title: throw +slug: Web/JavaScript/Referencje/Polecenia/throw +tags: + - Dokumentacja_JavaScript + - Dokumentacje + - JavaScript + - Strony_wymagające_dopracowania + - Wszystkie_kategorie +translation_of: Web/JavaScript/Reference/Statements/throw +--- +
{{jsSidebar("Statements")}}
+ +

The throw statement throws a user-defined exception. Execution of the current function will stop (the statements after throw won't be executed), and control will be passed to the first catch block in the call stack. If no catch block exists among caller functions, the program will terminate.

+ +
{{EmbedInteractiveExample("pages/js/statement-throw.html")}}
+ + +

Syntax

+ +
throw expression; 
+ +
+
expression
+
The expression to throw.
+
+ +

Description

+ +

Use the throw statement to throw an exception. When you throw an exception, expression specifies the value of the exception. Each of the following throws an exception:

+ +
throw 'Error2'; // generates an exception with a string value
+throw 42;       // generates an exception with the value 42
+throw true;     // generates an exception with the value true
+ +

Also note that the throw statement is affected by automatic semicolon insertion (ASI) as no line terminator between the throw keyword and the expression is allowed.

+ +

Examples

+ +

Throw an object

+ +

You can specify an object when you throw an exception. You can then reference the object's properties in the catch block. The following example creates an object of type UserException and uses it in a throw statement.

+ +
function UserException(message) {
+   this.message = message;
+   this.name = 'UserException';
+}
+function getMonthName(mo) {
+   mo = mo - 1; // Adjust month number for array index (1 = Jan, 12 = Dec)
+   var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul',
+      'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
+   if (months[mo] !== undefined) {
+      return months[mo];
+   } else {
+      throw new UserException('InvalidMonthNo');
+   }
+}
+
+try {
+   // statements to try
+   var myMonth = 15; // 15 is out of bound to raise the exception
+   var monthName = getMonthName(myMonth);
+} catch (e) {
+   monthName = 'unknown';
+   console.log(e.message, e.name); // pass exception object to err handler
+}
+
+ +

Another example of throwing an object

+ +

The following example tests an input string for a U.S. zip code. If the zip code uses an invalid format, the throw statement throws an exception by creating an object of type ZipCodeFormatException.

+ +
/*
+ * Creates a ZipCode object.
+ *
+ * Accepted formats for a zip code are:
+ *    12345
+ *    12345-6789
+ *    123456789
+ *    12345 6789
+ *
+ * If the argument passed to the ZipCode constructor does not
+ * conform to one of these patterns, an exception is thrown.
+ */
+
+function ZipCode(zip) {
+   zip = new String(zip);
+   pattern = /[0-9]{5}([- ]?[0-9]{4})?/;
+   if (pattern.test(zip)) {
+      // zip code value will be the first match in the string
+      this.value = zip.match(pattern)[0];
+      this.valueOf = function() {
+         return this.value
+      };
+      this.toString = function() {
+         return String(this.value)
+      };
+   } else {
+      throw new ZipCodeFormatException(zip);
+   }
+}
+
+function ZipCodeFormatException(value) {
+   this.value = value;
+   this.message = 'does not conform to the expected format for a zip code';
+   this.toString = function() {
+      return this.value + this.message;
+   };
+}
+
+/*
+ * This could be in a script that validates address data
+ * for US addresses.
+ */
+
+const ZIPCODE_INVALID = -1;
+const ZIPCODE_UNKNOWN_ERROR = -2;
+
+function verifyZipCode(z) {
+   try {
+      z = new ZipCode(z);
+   } catch (e) {
+      if (e instanceof ZipCodeFormatException) {
+         return ZIPCODE_INVALID;
+      } else {
+         return ZIPCODE_UNKNOWN_ERROR;
+      }
+   }
+   return z;
+}
+
+a = verifyZipCode(95060);         // returns 95060
+b = verifyZipCode(9560);          // returns -1
+c = verifyZipCode('a');           // returns -1
+d = verifyZipCode('95060');       // returns 95060
+e = verifyZipCode('95060 1234');  // returns 95060 1234
+
+ +

Rethrow an exception

+ +

You can use throw to rethrow an exception after you catch it. The following example catches an exception with a numeric value and rethrows it if the value is over 50. The rethrown exception propagates up to the enclosing function or to the top level so that the user sees it.

+ +
try {
+   throw n; // throws an exception with a numeric value
+} catch (e) {
+   if (e <= 50) {
+      // statements to handle exceptions 1-50
+   } else {
+      // cannot handle this exception, so rethrow
+      throw e;
+   }
+}
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.4
{{SpecName('ES5.1', '#sec-12.13', 'throw statement')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-throw-statement', 'throw statement')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-throw-statement', 'throw statement')}}{{Spec2('ESDraft')}}
+ +

Browser compatibility

+ + + +

{{Compat("javascript.statements.throw")}}

+ +

See also

+ + diff --git a/files/pl/web/javascript/reference/statements/var/index.html b/files/pl/web/javascript/reference/statements/var/index.html new file mode 100644 index 0000000000..aff42bcdac --- /dev/null +++ b/files/pl/web/javascript/reference/statements/var/index.html @@ -0,0 +1,61 @@ +--- +title: var +slug: Web/JavaScript/Referencje/Polecenia/var +tags: + - Dokumentacja_JavaScript + - Dokumentacje + - JavaScript + - Wszystkie_kategorie +translation_of: Web/JavaScript/Reference/Statements/var +--- +

+

+

Podsumowanie

+

Deklaruje zmienną oraz opcjonalnie przypisuje jej wartość początkową. +

+ + + + + + + + + + + + +
Instrukcja
Zaimplementowana w:JavaScript 1.0, NES 2.0
Wersja ECMA:ECMA-262
+

Składnia

+

+var varname1 {{ mediawiki.external('= value1') }}, varname2 {{ mediawiki.external('= value2') }}, ..., varnameN {{ mediawiki.external('= valueN') }}; + +

+

Parametry

+
varnameN 
Nazwa zmiennej. Może być dowolnym, dozwolonym identyfikatorem. +
+
valueN 
Zainicjalizowanie wartości zmiennej. Może być dowolnym, dozwolonym wyrażeniem. +
+

Opis

+

Zasięgiem zmiennej jest aktualna funkcja lub, jeśli zmienna została zadeklarowana poza funkcją, aktualna aplikacja. +

Użycie var poza funkcją jest opcjonalne; przypisanie wartości do niezadeklarowanej zmiennej domyślnie deklaruje ją jako zmienna globalną. Zalecane jest jednak, aby zawsze używać var, ponadto jest to konieczne wewnątrz funkcji w następujących przypadkach: +

+ +

Niepowodzenie zadeklarowania zmiennej w tych przypadkach będzie najprawdopodobniej prowadzić do niespodziewanych wyników. +

+

Przykłady

+

Przykład: Zastosowanie var

+

Poniższy przykład deklaruje dwie zmienne, num_hits i cust_no i przypisuje im obu początkową wartość 0. +

+
var num_hits = 0, cust_no = 0;
+
+

Zobacz także

+

const +


+


+

+
+
+{{ languages( { "en": "en/Core_JavaScript_1.5_Reference/Statements/var", "es": "es/Referencia_de_JavaScript_1.5/Sentencias/var", "fr": "fr/R\u00e9f\u00e9rence_de_JavaScript_1.5_Core/Instructions/var", "ja": "ja/Core_JavaScript_1.5_Reference/Statements/var" } ) }} diff --git a/files/pl/web/javascript/reference/statements/while/index.html b/files/pl/web/javascript/reference/statements/while/index.html new file mode 100644 index 0000000000..103762fd01 --- /dev/null +++ b/files/pl/web/javascript/reference/statements/while/index.html @@ -0,0 +1,61 @@ +--- +title: while +slug: Web/JavaScript/Referencje/Polecenia/while +tags: + - Dokumentacja_JavaScript + - Dokumentacje + - JavaScript + - Wszystkie_kategorie +translation_of: Web/JavaScript/Reference/Statements/while +--- +

+

+

Podsumowanie

+

Tworzy pętlę, która wylicza wyrażenie i, jeśli jest ono prawdą, wykonuje blok poleceń. Wykonywanie pętli powtarza się, póki warunek jest prawdziwy. +

+ + + + + + + + + + + + +
Polecenie
Zaimplementowane w:JavaScript 1.0, NES 2.0
Wersja ECMA:ECMA-262
+

Składnia

+
while (warunek) {
+  polecenia
+}
+
+

Parametery

+
warunek 
Wyliczany przed każdym wejściem w blok poleceń. Jeśli warunek jest prawdą, polecenia w bloku są wykonywane. Jeśli nie jest, sterowanie przepływa do pierwszego polecenia za pętlą. +
+
polecenia 
Blok poleceń wykonywanych póki warunek jest spełniony. Dobrą praktyką jest stosowanie w tym miejscu wcięć (indentacji), zwiększających czytelność kodu. +
+

Przykłady

+

Poniższa pętla while wykonuje się dopóki n jest mniejsze niż trzy. +

+
n = 0;
+x = 0;
+while(n < 3) {
+  n ++;
+  x += n;
+}
+
+

Po każdej iteracji pętla zwiększa n i dodaje je do x. Dlatego też x i n przyjmują następujące wartości: +

+ +

Po ukończeniu trzeciego przejścia warunek n < 3 nie jest już spełniony, zatem wykonywanie pętli kończy się. +


+


+

+
+
+{{ languages( { "en": "en/Core_JavaScript_1.5_Reference/Statements/while", "es": "es/Referencia_de_JavaScript_1.5/Sentencias/while", "fr": "fr/R\u00e9f\u00e9rence_de_JavaScript_1.5_Core/Instructions/while", "ja": "ja/Core_JavaScript_1.5_Reference/Statements/while" } ) }} -- cgit v1.2.3-54-g00ecf