From 1109132f09d75da9a28b649c7677bb6ce07c40c0 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:41:45 -0500 Subject: initial commit --- .../errors/bad_return_or_yield/index.html | 54 +++ .../hu/web/javascript/reference/errors/index.html | 31 ++ .../reference/errors/stmt_after_return/index.html | 67 +++ .../reference/errors/unexpected_token/index.html | 46 ++ .../index.html" | 70 +++ .../reference/global_objects/array/index.html | 538 +++++++++++++++++++++ .../reference/global_objects/array/keys/index.html | 77 +++ .../reference/global_objects/array/of/index.html | 94 ++++ .../reference/global_objects/array/sort/index.html | 294 +++++++++++ .../reference/global_objects/error/index.html | 218 +++++++++ .../f\303\274ggv\303\251ny/index.html" | 112 +++++ .../javascript/reference/global_objects/index.html | 192 ++++++++ .../reference/global_objects/nan/index.html | 96 ++++ .../reference/global_objects/string/index.html | 307 ++++++++++++ files/hu/web/javascript/reference/index.html | 197 ++++++++ .../web/javascript/reference/statements/index.html | 131 +++++ .../reference/statements/try...catch/index.html | 321 ++++++++++++ 17 files changed, 2845 insertions(+) create mode 100644 files/hu/web/javascript/reference/errors/bad_return_or_yield/index.html create mode 100644 files/hu/web/javascript/reference/errors/index.html create mode 100644 files/hu/web/javascript/reference/errors/stmt_after_return/index.html create mode 100644 files/hu/web/javascript/reference/errors/unexpected_token/index.html create mode 100644 "files/hu/web/javascript/reference/errors/\303\251rv\303\251nytelen_t\303\255pus/index.html" create mode 100644 files/hu/web/javascript/reference/global_objects/array/index.html create mode 100644 files/hu/web/javascript/reference/global_objects/array/keys/index.html create mode 100644 files/hu/web/javascript/reference/global_objects/array/of/index.html create mode 100644 files/hu/web/javascript/reference/global_objects/array/sort/index.html create mode 100644 files/hu/web/javascript/reference/global_objects/error/index.html create mode 100644 "files/hu/web/javascript/reference/global_objects/f\303\274ggv\303\251ny/index.html" create mode 100644 files/hu/web/javascript/reference/global_objects/index.html create mode 100644 files/hu/web/javascript/reference/global_objects/nan/index.html create mode 100644 files/hu/web/javascript/reference/global_objects/string/index.html create mode 100644 files/hu/web/javascript/reference/index.html create mode 100644 files/hu/web/javascript/reference/statements/index.html create mode 100644 files/hu/web/javascript/reference/statements/try...catch/index.html (limited to 'files/hu/web/javascript/reference') diff --git a/files/hu/web/javascript/reference/errors/bad_return_or_yield/index.html b/files/hu/web/javascript/reference/errors/bad_return_or_yield/index.html new file mode 100644 index 0000000000..2892367f9a --- /dev/null +++ b/files/hu/web/javascript/reference/errors/bad_return_or_yield/index.html @@ -0,0 +1,54 @@ +--- +title: 'Hibaleírás: SyntaxError: return not in function' +slug: Web/JavaScript/Reference/Errors/Bad_return_or_yield +tags: + - Error +translation_of: Web/JavaScript/Reference/Errors/Bad_return_or_yield +--- +
{{jsSidebar("Errors")}}
+ +

Üzenet

+ +
SyntaxError: 'return' statement outside of function (Edge)
+SyntaxError: return not in function (Firefox)
+SyntaxError: yield not in function (Firefox)
+
+ +

Hiba típusa

+ +

{{jsxref("SyntaxError")}}.

+ +

Mi történt?

+ +

Egy  return vagy yield utasítás szerepel function-ön kívül. Lehet, hogy egy kapcsos zárójel hiányzik? A return és yield utasításoknak függvényen belül kell szerepelniük, mert csak itt értelmezhetőek. (Megszakítják illetve megállítják-folytatják a proramrész futását, és opcionálisan értékrt adnak vissza.)

+ +

Példák

+ +
var cheer = function(score) {
+  if (score === 147)
+    return 'Maximum!';
+  };
+  if (score > 100) {
+    return 'Century!';
+  }
+}
+
+// SyntaxError: return not in function
+ +

A kapcsos zárójelek első ránézésre jól vannak rendezve, de a kódrészletből hiányzik egy { az első if utasítás után. A helyes kód így nézne ki:

+ +
var cheer = function(score) {
+  if (score === 147) {
+    return 'Maximum!';
+  }
+  if (score > 100) {
+    return 'Century!';
+  }
+};
+ +

Lásd még

+ + diff --git a/files/hu/web/javascript/reference/errors/index.html b/files/hu/web/javascript/reference/errors/index.html new file mode 100644 index 0000000000..c295fccea6 --- /dev/null +++ b/files/hu/web/javascript/reference/errors/index.html @@ -0,0 +1,31 @@ +--- +title: JavaScript error reference +slug: Web/JavaScript/Reference/Errors +tags: + - Debugging + - Error + - Errors + - Exception + - JavaScript + - NeedsTranslation + - TopicStub + - exceptions +translation_of: Web/JavaScript/Reference/Errors +--- +

{{jsSidebar("Errors")}}

+ +

Below, you'll find a list of errors which are thrown by JavaScript. These errors can be a helpful debugging aid, but the reported problem isn't always immediately clear. The pages below will provide additional details about these errors. Each error is an object based upon the {{jsxref("Error")}} object, and has a name and a message.

+ +

Errors displayed in the Web console may include a link to the corresponding page below to help you quickly comprehend the problem in your code.

+ +

List of errors

+ +

In this list, each page is listed by name (the type of error) and message (a more detailed human-readable error message). Together, these two properties provide a starting point toward understanding and resolving the error. For more information, follow the links below!

+ +

{{ListSubPages("/en-US/docs/Web/JavaScript/Reference/Errors")}}

+ +

See also

+ + diff --git a/files/hu/web/javascript/reference/errors/stmt_after_return/index.html b/files/hu/web/javascript/reference/errors/stmt_after_return/index.html new file mode 100644 index 0000000000..038658955c --- /dev/null +++ b/files/hu/web/javascript/reference/errors/stmt_after_return/index.html @@ -0,0 +1,67 @@ +--- +title: 'Hibaleírás: Warning: unreachable code after return statement' +slug: Web/JavaScript/Reference/Errors/Stmt_after_return +translation_of: Web/JavaScript/Reference/Errors/Stmt_after_return +--- +
{{jsSidebar("Errors")}}
+ +

Üzenet

+ +
Warning: unreachable code after return statement (Firefox)
+
+ +

Hiba típusa

+ +

Figyelmeztetés

+ +

Mi történt?

+ +

A return utasítás befejezi a függvény végrehajtását, és opcionálisan értéket ad vissza. Ha return szerepel a függvényben közvetlenül (tehát nem if-be ágyazva), akkor a return mindig végrehajtódik. Ez esetben, ha a return után van még valamilyen kód, az soha nem fog végrehajtódni. Ezt jelzi a figyelmeztetés.

+ +

Ha a return után nincs pontosvessző, majd a következő sorban egy kifejezés (szám, string, ...) szerepel, a figyelmezetés akkor is megjelenik. A JavaScript ugyanis bizonyos esetekben az entert is pontosvesszőnek értelmezi, így a return utasítás lefut, a mögötte található kifejezés pedig nem lesz értelmezve.

+ +

Nem jelenik meg figyelmeztetés a pontosvessző nélküli returnre, ha az alábbi utasítások valamelyike követi:

+ + + +

Példák

+ +

Hibás használatok

+ +
function f() {
+  var x = 3;
+  x += 4;
+  return x;   // a return azonnal visszatér a függvényből
+  x -= 3;     // tehát ez a sor soha nem fog lefutni; nem elérhető
+}
+
+function f() {
+  return     // ez 'return'-ként értelmeződik
+    3 + 4;   // tehát a funkció visszatér és ezt a sort soha nem éri el
+}
+
+ +

Helyes használat

+ +
function f() {
+  var x = 3;
+  x += 4;
+  x -= 3;
+  return x;  // OK: visszatér minden más utasítás után
+}
+
+function f() {
+  return 3 + 4  // OK: pontosvessző nélküli return, kifejezéssel ugyanazon sorban
+}
+
+ +

Lásd még

+ + diff --git a/files/hu/web/javascript/reference/errors/unexpected_token/index.html b/files/hu/web/javascript/reference/errors/unexpected_token/index.html new file mode 100644 index 0000000000..6e6640b551 --- /dev/null +++ b/files/hu/web/javascript/reference/errors/unexpected_token/index.html @@ -0,0 +1,46 @@ +--- +title: 'SyntaxError: Unexpected token' +slug: Web/JavaScript/Reference/Errors/Unexpected_token +translation_of: Web/JavaScript/Reference/Errors/Unexpected_token +--- +
{{jsSidebar("Errors")}}
+ +

Üzenet

+ +
SyntaxError: expected expression, got "x"
+SyntaxError: expected property name, got "x"
+SyntaxError: expected target, got "x"
+SyntaxError: expected rest argument name, got "x"
+SyntaxError: expected closing parenthesis, got "x"
+SyntaxError: expected '=>' after argument list, got "x"
+
+ +

Hiba Típusa

+ +

{{jsxref("SyntaxError")}}

+ +

Mi nem jó?

+ +

A nyelv specifikációja várna egy bizonyos nyelvi formát, de az nem teljesül. Valószínűleg ez egy egyszerű elírás.

+ +

Példák

+ +

Várható kifejezések

+ +

Például, ha egy függvény egy lezáró vesszővel hívünk meg, ez nem helyes. Ugyanis a JavaScript egy argumentumot vár ilyenkor, ami bármilyen bárilyen kifejezés is lehet.

+ +
Math.max(2, 42,);
+// SyntaxError: expected expression, got ')'
+
+ +

Correct would be omitting the comma or adding another argument:

+ +
Math.max(2, 42);
+Math.max(2, 42, 13 + 37);
+
+ +

Lásd még

+ + diff --git "a/files/hu/web/javascript/reference/errors/\303\251rv\303\251nytelen_t\303\255pus/index.html" "b/files/hu/web/javascript/reference/errors/\303\251rv\303\251nytelen_t\303\255pus/index.html" new file mode 100644 index 0000000000..1fd4e782de --- /dev/null +++ "b/files/hu/web/javascript/reference/errors/\303\251rv\303\251nytelen_t\303\255pus/index.html" @@ -0,0 +1,70 @@ +--- +title: 'Típushiba: "x" (nem) "y"' +slug: Web/JavaScript/Reference/Errors/Érvénytelen_típus +translation_of: Web/JavaScript/Reference/Errors/Unexpected_type +--- +
{{jsSidebar("Errors")}}
+ +
Az „x (nem) y” JavaScript-kivétel akkor keletkezik, ha egy váratlan típus fordul elő. Ez leginkább váratlan {{jsxref("undefined")}} vagy {{jsxref("null")}} értéket jelent.
+ +

Üzenet

+ +
TypeError: Unable to get property {x} of undefined or null reference (Edge)
+TypeError: "x" is (not) "y" (Firefox)
+
+Példák:
+TypeError: "x" is undefined
+TypeError: "x" is null
+TypeError: "undefined" is not an object
+TypeError: "x" is not an object or null
+TypeError: "x" is not a symbol
+
+ +

Hiba típusa

+ +

{{jsxref("TypeError")}}.

+ +

Mi történt?

+ +

Váratlan típus fordult elő a végrehajtás során. Ez leginkább {{jsxref("undefined")}} vagy {{jsxref("null")}} értékek esetén történik.

+ +

Ugyanígy bizonyos metódusok – mint például az {{jsxref("Object.create()")}} vagy a {{jsxref("Symbol.keyFor()")}} – paraméterként egy meghatározott típust várnak.

+ +

Példák

+ +

Hibás használatok

+ +
// nem definiált és null értékű paraméterek használata, amiknek esetén a substring metódus nem működik
+var foo = undefined;
+foo.substring(1); // TypeError: foo nincs definiálva
+
+var foo = null;
+foo.substring(1); // TypeError: foo értéke null
+
+
+// Bizonyos metódusok meghatározott típust várnak el
+var foo = {}
+Symbol.keyFor(foo); // TypeError: foo nem szimbólum
+
+var foo = 'bar'
+Object.create(foo); // TypeError: "foo" nem objektum vagy null értékű
+
+ +

A hiba javítása

+ +

Az undefined értékek kiszűrésére például a typeof operátort lehet használni.

+ +
if (foo !== undefined) {
+  // Most, hogy tudjuk foo definiálva van, léphetünk tovább.
+}
+if (typeof foo !== 'undefined') {
+  // Ugyanaz a jó ötlet, de nem használandó implementáció – problémákat tud okozni
+  // a ténylegesen definiálatlan és a deklarálatlan változók közötti kavarodás miatt.
+}
+ +

Lásd még

+ + diff --git a/files/hu/web/javascript/reference/global_objects/array/index.html b/files/hu/web/javascript/reference/global_objects/array/index.html new file mode 100644 index 0000000000..2feb1828f9 --- /dev/null +++ b/files/hu/web/javascript/reference/global_objects/array/index.html @@ -0,0 +1,538 @@ +--- +title: Array +slug: Web/JavaScript/Reference/Global_Objects/Array +tags: + - Array + - Example + - Global Objects + - JavaScript + - NeedsTranslation + - Reference + - TopicStub +translation_of: Web/JavaScript/Reference/Global_Objects/Array +--- +
{{JSRef}}
+ +

Tömbök, amelyek magas-szintű lista jellegű objektumok, létrehozásához használatos a JavaScript Array objektum.

+ +

Leírás

+ +

A tömbök listaszerű objektumok amelyek prototípusa olyan metódusokat tartalmaz  amelyekkel bejárhatóak és mutálhatóak. A JavaScipt tömbnek sem a hossza, sem az elemeinek típusa sem fix. A tömbön belül az adatok nem folytonos módon tárolhatóak, így mivel a tömb hossza bármikor megváltozhat a Javascript tömbök sürűsége nem garantált, ez a programozó által választott felhasználási módtól függ. Általánosságban ezek kényelmes tulajdonságok de ha ezek a jellemzők nem kívánatosak az ön számára érdemes lehet inkább típusos tömböket használni. A tömbök nem használhatnak stringeket elem indexként (mint egy asszociatív tömbben) csak kötelezően integereket. Ha a zárójel jelölés (vagy pont jelölés) segítségével nem-integert állítunk be vagy férünk hozzá akkor nem a tömb elemét fogjuk megkapni hanem a tömb objektum tulajdonság kollekciójának változóját. A tömb elemeinek listája és a tömb objektum tulajdonságai különböznek és a tömb bejáró és mutáló operátorait nem használhatjuk ezekhez az elnevezett tulajdonságokhoz.

+ +

Gyakori műveletek

+ +

Array létrehozása

+ +
var fruits = ["Apple", "Banana"];
+
+console.log(fruits.length);
+// 2
+
+ +

Egy Array elem elérése (indexelése)

+ +
var first = fruits[0];
+// Apple
+
+var last = fruits[fruits.length - 1];
+// Banana
+
+ +

Array bejárása

+ +
fruits.forEach(function (item, index, array) {
+  console.log(item, index);
+});
+// Apple 0
+// Banana 1
+
+ +

Hozzáadás egy Array végéhez

+ +
var newLength = fruits.push("Orange");
+// ["Apple", "Banana", "Orange"]
+
+ +

Array végéről elem eltávolítása

+ +
var last = fruits.pop(); // Orange eltávolítása (a végéről)
+// ["Apple", "Banana"];
+
+ +

Array elejéről elem eltávolítása

+ +
var first = fruits.shift(); // eltávolítja az Apple elemet az elejéről
+// ["Banana"];
+
+ +

Array elejéhez hozzáadás

+ +
var newLength = fruits.unshift("Strawberry") // hozzáadás az elejéhez
+// ["Strawberry", "Banana"];
+
+ +

Array elem indexének megkeresése

+ +
fruits.push("Mango");
+// ["Strawberry", "Banana", "Mango"]
+
+var pos = fruits.indexOf("Banana");
+// 1
+
+ +

Index pozició alapján elem eltávolítása

+ +
var removedItem = fruits.splice(pos, 1); // így távolítunk el egy elemet
+
+// ["Strawberry", "Mango"]
+ +

Index pozició alapján elemek eltávolítása

+ +
let vegetables = ['Cabbage', 'Turnip', 'Radish', 'Carrot']
+console.log(vegetables)
+// ["Cabbage", "Turnip", "Radish", "Carrot"]
+
+let pos = 1
+let n = 2
+
+let removedItems = vegetables.splice(pos, n)
+// this is how to remove items, n defines the number of items to be removed,
+// from that position(pos) onward to the end of array.
+
+console.log(vegetables)
+// ["Cabbage", "Carrot"] (the original array is changed)
+
+console.log(removedItems)
+// ["Turnip", "Radish"]
+ +

Array másolása

+ +
var shallowCopy = fruits.slice(); // this is how to make a copy
+// ["Strawberry"]
+
+ +

Syntax

+ +
[element0, element1, ..., elementN]
+new Array(element0, element1[, ...[, elementN]])
+new Array(arrayLength)
+ +

Parameters

+ +
+
elementN
+
A JavaScript array is initialized with the given elements, except in the case where a single argument is passed to the Array constructor and that argument is a number (see the arrayLength parameter below). Note that this special case only applies to JavaScript arrays created with the Array constructor, not array literals created with the bracket syntax.
+
arrayLength
+
If the only argument passed to the Array constructor is an integer between 0 and 232-1 (inclusive), this returns a new JavaScript array with length set to that number. If the argument is any other number, a {{jsxref("RangeError")}} exception is thrown.
+
+ +

Description

+ +

Arrays are list-like objects whose prototype has methods to perform traversal and mutation operations. Neither the length of a JavaScript array nor the types of its elements are fixed. Since an array's length can change at any time, and data can be stored at non-contiguous locations in the array, JavaScript arrays are not guaranteed to be dense; this depends on how the programmer chooses to use them. In general, these are convenient characteristics; but if these features are not desirable for your particular use, you might consider using typed arrays.

+ +

Some people think that you shouldn't use an array as an associative array. In any case, you can use plain {{jsxref("Global_Objects/Object", "objects")}} instead, although doing so comes with its own caveats. See the post Lightweight JavaScript dictionaries with arbitrary keys as an example.

+ +

Accessing array elements

+ +

JavaScript arrays are zero-indexed: the first element of an array is at index 0, and the last element is at the index equal to the value of the array's {{jsxref("Array.length", "length")}} property minus 1.

+ +
var arr = ['this is the first element', 'this is the second element'];
+console.log(arr[0]);              // logs 'this is the first element'
+console.log(arr[1]);              // logs 'this is the second element'
+console.log(arr[arr.length - 1]); // logs 'this is the second element'
+
+ +

Array elements are object properties in the same way that toString is a property, but trying to access an element of an array as follows throws a syntax error, because the property name is not valid:

+ +
console.log(arr.0); // a syntax error
+
+ +

There is nothing special about JavaScript arrays and the properties that cause this. JavaScript properties that begin with a digit cannot be referenced with dot notation; and must be accessed using bracket notation. For example, if you had an object with a property named '3d', it can only be referenced using bracket notation. E.g.:

+ +
var years = [1950, 1960, 1970, 1980, 1990, 2000, 2010];
+console.log(years.0);   // a syntax error
+console.log(years[0]);  // works properly
+
+ +
renderer.3d.setTexture(model, 'character.png');     // a syntax error
+renderer['3d'].setTexture(model, 'character.png');  // works properly
+
+ +

Note that in the 3d example, '3d' had to be quoted. It's possible to quote the JavaScript array indexes as well (e.g., years['2'] instead of years[2]), although it's not necessary. The 2 in years[2] is coerced into a string by the JavaScript engine through an implicit toString conversion. It is for this reason that '2' and '02' would refer to two different slots on the years object and the following example could be true:

+ +
console.log(years['2'] != years['02']);
+
+ +

Similarly, object properties which happen to be reserved words(!) can only be accessed as string literals in bracket notation(but it can be accessed by dot notation in firefox 40.0a2 at least):

+ +
var promise = {
+  'var'  : 'text',
+  'array': [1, 2, 3, 4]
+};
+
+console.log(promise['array']);
+
+ +

Relationship between length and numerical properties

+ +

A JavaScript array's {{jsxref("Array.length", "length")}} property and numerical properties are connected. Several of the built-in array methods (e.g., {{jsxref("Array.join", "join")}}, {{jsxref("Array.slice", "slice")}}, {{jsxref("Array.indexOf", "indexOf")}}, etc.) take into account the value of an array's {{jsxref("Array.length", "length")}} property when they're called. Other methods (e.g., {{jsxref("Array.push", "push")}}, {{jsxref("Array.splice", "splice")}}, etc.) also result in updates to an array's {{jsxref("Array.length", "length")}} property.

+ +
var fruits = [];
+fruits.push('banana', 'apple', 'peach');
+
+console.log(fruits.length); // 3
+
+ +

When setting a property on a JavaScript array when the property is a valid array index and that index is outside the current bounds of the array, the engine will update the array's {{jsxref("Array.length", "length")}} property accordingly:

+ +
fruits[5] = 'mango';
+console.log(fruits[5]); // 'mango'
+console.log(Object.keys(fruits));  // ['0', '1', '2', '5']
+console.log(fruits.length); // 6
+
+ +

Increasing the {{jsxref("Array.length", "length")}}.

+ +
fruits.length = 10;
+console.log(Object.keys(fruits)); // ['0', '1', '2', '5']
+console.log(fruits.length); // 10
+
+ +

Decreasing the {{jsxref("Array.length", "length")}} property does, however, delete elements.

+ +
fruits.length = 2;
+console.log(Object.keys(fruits)); // ['0', '1']
+console.log(fruits.length); // 2
+
+ +

This is explained further on the {{jsxref("Array.length")}} page.

+ +

Creating an array using the result of a match

+ +

The result of a match between a regular expression and a string can create a JavaScript array. This array has properties and elements which provide information about the match. Such an array is returned by {{jsxref("RegExp.exec")}}, {{jsxref("String.match")}}, and {{jsxref("String.replace")}}. To help explain these properties and elements, look at the following example and then refer to the table below:

+ +
// Match one d followed by one or more b's followed by one d
+// Remember matched b's and the following d
+// Ignore case
+
+var myRe = /d(b+)(d)/i;
+var myArray = myRe.exec('cdbBdbsbz');
+
+ +

The properties and elements returned from this match are as follows:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Property/ElementDescriptionExample
inputA read-only property that reflects the original string against which the regular expression was matched.cdbBdbsbz
indexA read-only property that is the zero-based index of the match in the string.1
[0]A read-only element that specifies the last matched characters.dbBd
[1], ...[n]Read-only elements that specify the parenthesized substring matches, if included in the regular expression. The number of possible parenthesized substrings is unlimited.[1]: bB
+ [2]: d
+ +

Properties

+ +
+
Array.length
+
The Array constructor's length property whose value is 1.
+
{{jsxref("Array.@@species", "get Array[@@species]")}}
+
The constructor function that is used to create derived objects.
+
{{jsxref("Array.prototype")}}
+
Allows the addition of properties to all array objects.
+
+ +

Methods

+ +
+
{{jsxref("Array.from()")}}
+
Creates a new Array instance from an array-like or iterable object.
+
{{jsxref("Array.isArray()")}}
+
Returns true if a variable is an array, if not false.
+
{{jsxref("Array.of()")}}
+
Creates a new Array instance with a variable number of arguments, regardless of number or type of the arguments.
+
+ +

Array instances

+ +

All Array instances inherit from {{jsxref("Array.prototype")}}. The prototype object of the Array constructor can be modified to affect all Array instances.

+ +

Properties

+ +
{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype', 'Properties')}}
+ +

Methods

+ +

Mutator methods

+ +
{{page('en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype', 'Mutator_methods')}}
+ +

Accessor methods

+ +
{{page('en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype', 'Accessor_methods')}}
+ +

Iteration methods

+ +
{{page('en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype', 'Iteration_methods')}}
+ +

Array generic methods

+ +
+

Array generics are non-standard, deprecated and will get removed in the near future. Note that you can not rely on them cross-browser. However, there is a shim available on GitHub.

+
+ +

Sometimes you would like to apply array methods to strings or other array-like objects (such as function {{jsxref("Functions/arguments", "arguments", "", 1)}}). By doing this, you treat a string as an array of characters (or otherwise treat a non-array as an array). For example, in order to check that every character in the variable str is a letter, you would write:

+ +
function isLetter(character) {
+  return character >= 'a' && character <= 'z';
+}
+
+if (Array.prototype.every.call(str, isLetter)) {
+  console.log("The string '" + str + "' contains only letters!");
+}
+
+ +

This notation is rather wasteful and JavaScript 1.6 introduced a generic shorthand:

+ +
if (Array.every(str, isLetter)) {
+  console.log("The string '" + str + "' contains only letters!");
+}
+
+ +

{{jsxref("Global_Objects/String", "Generics", "#String_generic_methods", 1)}} are also available on {{jsxref("String")}}.

+ +

These are not part of ECMAScript standards (though the ES2015 {{jsxref("Array.from()")}} can be used to achieve this). The following is a shim to allow its use in all browsers:

+ +
// Assumes Array extras already present (one may use polyfills for these as well)
+(function() {
+  'use strict';
+
+  var i,
+    // We could also build the array of methods with the following, but the
+    //   getOwnPropertyNames() method is non-shimable:
+    // Object.getOwnPropertyNames(Array).filter(function(methodName) {
+    //   return typeof Array[methodName] === 'function'
+    // });
+    methods = [
+      'join', 'reverse', 'sort', 'push', 'pop', 'shift', 'unshift',
+      'splice', 'concat', 'slice', 'indexOf', 'lastIndexOf',
+      'forEach', 'map', 'reduce', 'reduceRight', 'filter',
+      'some', 'every', 'find', 'findIndex', 'entries', 'keys',
+      'values', 'copyWithin', 'includes'
+    ],
+    methodCount = methods.length,
+    assignArrayGeneric = function(methodName) {
+      if (!Array[methodName]) {
+        var method = Array.prototype[methodName];
+        if (typeof method === 'function') {
+          Array[methodName] = function() {
+            return method.call.apply(method, arguments);
+          };
+        }
+      }
+    };
+
+  for (i = 0; i < methodCount; i++) {
+    assignArrayGeneric(methods[i]);
+  }
+}());
+
+ +

Examples

+ +

Creating an array

+ +

The following example creates an array, msgArray, with a length of 0, then assigns values to msgArray[0] and msgArray[99], changing the length of the array to 100.

+ +
var msgArray = [];
+msgArray[0] = 'Hello';
+msgArray[99] = 'world';
+
+if (msgArray.length === 100) {
+  console.log('The length is 100.');
+}
+
+ +

Creating a two-dimensional array

+ +

The following creates a chess board as a two dimensional array of strings. The first move is made by copying the 'p' in (6,4) to (4,4). The old position (6,4) is made blank.

+ +
var board = [
+  ['R','N','B','Q','K','B','N','R'],
+  ['P','P','P','P','P','P','P','P'],
+  [' ',' ',' ',' ',' ',' ',' ',' '],
+  [' ',' ',' ',' ',' ',' ',' ',' '],
+  [' ',' ',' ',' ',' ',' ',' ',' '],
+  [' ',' ',' ',' ',' ',' ',' ',' '],
+  ['p','p','p','p','p','p','p','p'],
+  ['r','n','b','q','k','b','n','r'] ];
+
+console.log(board.join('\n') + '\n\n');
+
+// Move King's Pawn forward 2
+board[4][4] = board[6][4];
+board[6][4] = ' ';
+console.log(board.join('\n'));
+
+ +

Here is the output:

+ +
R,N,B,Q,K,B,N,R
+P,P,P,P,P,P,P,P
+ , , , , , , ,
+ , , , , , , ,
+ , , , , , , ,
+ , , , , , , ,
+p,p,p,p,p,p,p,p
+r,n,b,q,k,b,n,r
+
+R,N,B,Q,K,B,N,R
+P,P,P,P,P,P,P,P
+ , , , , , , ,
+ , , , , , , ,
+ , , , ,p, , ,
+ , , , , , , ,
+p,p,p,p, ,p,p,p
+r,n,b,q,k,b,n,r
+
+ +

Using an array to tabulate a set of values

+ +
values=[];
+for (x=0; x<10; x++){
+ values.push([
+  2**x,
+  2*x**2
+ ])
+};
+console.table(values)
+ +

Results in

+ +
0	1	0
+1	2	2
+2	4	8
+3	8	18
+4	16	32
+5	32	50
+6	64	72
+7	128	98
+8	256	128
+9	512	162
+ +

(First column is the (index))

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition.
{{SpecName('ES5.1', '#sec-15.4', 'Array')}}{{Spec2('ES5.1')}}New methods added: {{jsxref("Array.isArray")}}, {{jsxref("Array.prototype.indexOf", "indexOf")}}, {{jsxref("Array.prototype.lastIndexOf", "lastIndexOf")}}, {{jsxref("Array.prototype.every", "every")}}, {{jsxref("Array.prototype.some", "some")}}, {{jsxref("Array.prototype.forEach", "forEach")}}, {{jsxref("Array.prototype.map", "map")}}, {{jsxref("Array.prototype.filter", "filter")}}, {{jsxref("Array.prototype.reduce", "reduce")}}, {{jsxref("Array.prototype.reduceRight", "reduceRight")}}
{{SpecName('ES6', '#sec-array-objects', 'Array')}}{{Spec2('ES6')}}New methods added: {{jsxref("Array.from")}}, {{jsxref("Array.of")}}, {{jsxref("Array.prototype.find", "find")}}, {{jsxref("Array.prototype.findIndex", "findIndex")}}, {{jsxref("Array.prototype.fill", "fill")}}, {{jsxref("Array.prototype.copyWithin", "copyWithin")}}
{{SpecName('ESDraft', '#sec-array-objects', 'Array')}}{{Spec2('ESDraft')}}New method added: {{jsxref("Array.prototype.includes()")}}
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

See also

+ + diff --git a/files/hu/web/javascript/reference/global_objects/array/keys/index.html b/files/hu/web/javascript/reference/global_objects/array/keys/index.html new file mode 100644 index 0000000000..2f7c0cebef --- /dev/null +++ b/files/hu/web/javascript/reference/global_objects/array/keys/index.html @@ -0,0 +1,77 @@ +--- +title: Array.prototype.keys() +slug: Web/JavaScript/Reference/Global_Objects/Array/keys +tags: + - ECMAScript 2015 + - Iterator + - JavaScript + - Prototype + - kulcs + - metódus + - tömb +translation_of: Web/JavaScript/Reference/Global_Objects/Array/keys +--- +
{{JSRef}}
+ +

A keys() metódus egy új Array Iterator objektummal tér vissza, amely a tömb indexeihez tartozó kulcsokat tartalmazza.

+ +
{{EmbedInteractiveExample("pages/js/array-keys.html")}}
+ + + +

Szintaxis

+ +
arr.keys()
+ +

Visszatérési érték

+ +

Egy új {{jsxref("Array")}} iterátor objektum.

+ +

Példák

+ +

A kulcs iterátor nem hagyja figyelmen kívül az üres helyeket

+ +
var arr = ['a', , 'c'];
+var sparseKeys = Object.keys(arr);
+var denseKeys = [...arr.keys()];
+console.log(sparseKeys); // ['0', '2']
+console.log(denseKeys);  // [0, 1, 2]
+
+ +

Specifikációk

+ + + + + + + + + + + + + + + + + + + +
SpecifikációStátuszMegjegyzés
{{SpecName('ES2015', '#sec-array.prototype.keys', 'Array.prototype.keys')}}{{Spec2('ES2015')}}Kezdeti definíció.
{{SpecName('ESDraft', '#sec-array.prototype.keys', 'Array.prototype.keys')}}{{Spec2('ESDraft')}} 
+ +

Böngésző kompatibilitás

+ +
+ + +

{{Compat("javascript.builtins.Array.keys")}}

+
+ +

Lásd még

+ + diff --git a/files/hu/web/javascript/reference/global_objects/array/of/index.html b/files/hu/web/javascript/reference/global_objects/array/of/index.html new file mode 100644 index 0000000000..ff3af4288a --- /dev/null +++ b/files/hu/web/javascript/reference/global_objects/array/of/index.html @@ -0,0 +1,94 @@ +--- +title: Array.of() +slug: Web/JavaScript/Reference/Global_Objects/Array/of +tags: + - tömb +translation_of: Web/JavaScript/Reference/Global_Objects/Array/of +--- +
{{JSRef}}
+ +

Az Array.of() metódus egy új Array példányt hoz létre változó számú argumentumokból, azok számától és típusától függetlenül.

+ +

Az Array.of() és az Array konstruktor működése között az a különbség, hogy máshogy hasznája az argumentumként megadott egész számokat: az Array.of(7) létrehoz egy új tömböt, melynek az egyetlen eleme a 7, ezzel szemben az Array(7) egy olyan üres tömböt hoz létre, melynek a length property-je: 7 (Megjegyzés: ez valójában egy 7 üres elemű (empty) tömböt jelent, nem olyat, melynek az elemei ténylegesen undefined értékeket tartalmaznának).

+ +
Array.of(7);       // [7]
+Array.of(1, 2, 3); // [1, 2, 3]
+
+Array(7);          // 7 üres elemű tömb: [empty × 7]
+Array(1, 2, 3);    // [1, 2, 3]
+
+ +

Szintakszis

+ +
Array.of(elem0[, elem1[, ...[, elemN]]])
+ +

Paraméterek

+ +
+
elemN
+
Elemek, melyeket a tömb tartalmazni fog
+
+ +

Visszatérési érték

+ +

Egy új {{jsxref("Array")}} példány.

+ +

Leírás

+ +

Ez a függvény szabványos az ECMAScript 2015 óta. További részletekért lásd az Array.of és az Array.from proposal-t és a Array.of polyfill-t.

+ +

Példák

+ +
Array.of(1);         // [1]
+Array.of(1, 2, 3);   // [1, 2, 3]
+Array.of(undefined); // [undefined]
+
+ +

Polyfill

+ +

A következő kód lefuttatása után az Array.of() hasznáható lesz, amennyiben a kliens ezt natíven nem támogatja.

+ +
if (!Array.of) {
+  Array.of = function() {
+    return Array.prototype.slice.call(arguments);
+  };
+}
+
+ +

Specifikációk

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-array.of', 'Array.of')}}{{Spec2('ES2015')}}Kezdeti definíció.
{{SpecName('ESDraft', '#sec-array.of', 'Array.of')}}{{Spec2('ESDraft')}}
+ +

Böngésző kompatibilitás

+ +
+ + +

{{Compat("javascript.builtins.Array.of")}}

+
+ +

Lásd még:

+ + diff --git a/files/hu/web/javascript/reference/global_objects/array/sort/index.html b/files/hu/web/javascript/reference/global_objects/array/sort/index.html new file mode 100644 index 0000000000..408507ddd8 --- /dev/null +++ b/files/hu/web/javascript/reference/global_objects/array/sort/index.html @@ -0,0 +1,294 @@ +--- +title: Array.prototype.sort() +slug: Web/JavaScript/Reference/Global_Objects/Array/sort +tags: + - Prototípus + - Rendezés + - metódus + - tömb +translation_of: Web/JavaScript/Reference/Global_Objects/Array/sort +--- +
{{JSRef}}
+ +

sort() eljárás  egy tömb elemeit rendezi helyben, és visszaadja a tömböt. Egy rendezés nem teljesen stabil. Az alapértelmezett rendezési sorrend függ a sztring Unicode táblában való elhelyezkedésétől.

+ +
var fruits = ['cherries', 'apples', 'banana'];
+fruits.sort(); // ['apple', 'banana', 'cherries']
+
+var scores = [1, 10, 21, 2];
+scores.sort(); // [1, 10, 2, 21]
+// Figyeld meg,hogy a 10 a 2 előtt jön,
+// mivel a '10' hamarabb van,mint '2' a Unicode sorolás szerint.
+
+var things = ['word', 'Word', '1 Word', '2 Words'];
+things.sort(); // ['1 Word', '2 Words', 'Word', 'word']
+// A Unicode-ban, a számok hamarabb kerülnek sorra mint a nagybetűk,
+// de, azok hamarabb vannak,mint a kisbetűk.
+
+ +

Szintaxis

+ +
arr.sort() arr.sort(compareFunction)
+
+ +

Paraméterek

+ +
+
compareFunction {{optional_inline}}
+
Meghatároz egy függvényt, amely definiálja  a rendezési sorrendet. Ha elhagyjuk, a tömb rendezése az egyes betűk Unicode táblában való elhelyezkedése alapján történik meg.
+
+ +

Visszatérési érték

+ +

A rendezett tömb. Vegyük figyelembe, hogy a rendezés helyben történt és nem készült másolat a tömbről.

+ +

Leírás

+ +

Ha a compareFunction nem mellékelt, akkor az elemek rendezése úgy zajlik, hogy először átkonvertálja sztringgé, majd összehasonlítja a Unicode karakter sorrendet. Például, "Banana" hamarabb lesz,mint "cherry". Szám-sorrendben a 9 hamarabb lesz 80-nál, de mivel a számok átkonvertálódnak sztringgé, "80" hamarabb lesz "9"-nél a Unicode sorolás szerint.

+ +

Ha compareFunction mellékelt, a tömb elemei rendezésre kerülnek az összehasonlító függvény visszatérési értéke alapján. Ha a és b elemek összehasonlításra kerülnek:

+ + + +

Szóval, az összehasonlító függvény így néz ki:

+ +
function compare(a, b) {
+  if (a kisebb mint b a sorrend kritéria szerint) {
+    return -1;
+  }
+  if (a nagyobb mint b a sorrend kritéria szerint) {
+    return 1;
+  }
+  // a-nak egyenlőnek kell lennie b-vel
+  return 0;
+}
+
+ +

To compare numbers instead of strings, the compare function can simply subtract b from a. The following function will sort the array ascending (if it doesn't contain Infinity and NaN):

+ +
function compareNumbers(a, b) {
+  return a - b;
+}
+
+ +

The sort method can be conveniently used with {{jsxref("Operators/function", "function expressions", "", 1)}} (and closures):

+ +
var numbers = [4, 2, 5, 1, 3];
+numbers.sort(function(a, b) {
+  return a - b;
+});
+console.log(numbers);
+
+// [1, 2, 3, 4, 5]
+
+ +

Objektumok is rendezhetőek, ha megadjuk az egyik tulajdonságát.

+ +
var items = [
+  { name: 'Edward', value: 21 },
+  { name: 'Sharpe', value: 37 },
+  { name: 'And', value: 45 },
+  { name: 'The', value: -12 },
+  { name: 'Magnetic', value: 13 },
+  { name: 'Zeros', value: 37 }
+];
+
+// sort by value
+items.sort(function (a, b) {
+  return a.value - b.value;
+});
+
+// sort by name
+items.sort(function(a, b) {
+  var nameA = a.name.toUpperCase(); // nagybetűk és kisbetűk elhagyása
+  var nameB = b.name.toUpperCase(); // nagybetűk és kisbetűk elhagyása
+  if (nameA < nameB) {
+    return -1;
+  }
+  if (nameA > nameB) {
+    return 1;
+  }
+
+  // a neveknek egyeznie kell
+  return 0;
+});
+ +

Példák

+ +

Tömbök készítése,megjelenítése és rendezése

+ +

A következő példa négy tömböt készít, megjeleníti az eredeti tömböt, majd a rendezett tömböket. A numerikus tömbök először nem,azután használva a compare függvényt rendezésre kerülnek.

+ +
var stringArray = ['Blue', 'Humpback', 'Beluga'];
+var numericStringArray = ['80', '9', '700'];
+var numberArray = [40, 1, 5, 200];
+var mixedNumericArray = ['80', '9', '700', 40, 1, 5, 200];
+
+function compareNumbers(a, b) {
+  return a - b;
+}
+
+console.log('stringArray:', stringArray.join());
+console.log('Sorted:', stringArray.sort());
+
+console.log('numberArray:', numberArray.join());
+console.log('Sorted without a compare function:', numberArray.sort());
+console.log('Sorted with compareNumbers:', numberArray.sort(compareNumbers));
+
+console.log('numericStringArray:', numericStringArray.join());
+console.log('Sorted without a compare function:', numericStringArray.sort());
+console.log('Sorted with compareNumbers:', numericStringArray.sort(compareNumbers));
+
+console.log('mixedNumericArray:', mixedNumericArray.join());
+console.log('Sorted without a compare function:', mixedNumericArray.sort());
+console.log('Sorted with compareNumbers:', mixedNumericArray.sort(compareNumbers));
+
+ +

This example produces the following output. As the output shows, when a compare function is used, numbers sort correctly whether they are numbers or numeric strings.

+ +
stringArray: Blue,Humpback,Beluga
+Sorted: Beluga,Blue,Humpback
+
+numberArray: 40,1,5,200
+Sorted without a compare function: 1,200,40,5
+Sorted with compareNumbers: 1,5,40,200
+
+numericStringArray: 80,9,700
+Sorted without a compare function: 700,80,9
+Sorted with compareNumbers: 9,80,700
+
+mixedNumericArray: 80,9,700,40,1,5,200
+Sorted without a compare function: 1,200,40,5,700,80,9
+Sorted with compareNumbers: 1,5,9,40,80,200,700
+
+ +

Nem-ASCII karakterek rendezése

+ +

For sorting strings with non-ASCII characters, i.e. strings with accented characters (e, é, è, a, ä, etc.), strings from languages other than English: use {{jsxref("String.localeCompare")}}. This function can compare those characters so they appear in the right order.

+ +
var items = ['réservé', 'premier', 'cliché', 'communiqué', 'café', 'adieu'];
+items.sort(function (a, b) {
+  return a.localeCompare(b);
+});
+
+// items is ['adieu', 'café', 'cliché', 'communiqué', 'premier', 'réservé']
+
+ +

Rendezés map-al

+ +

The compareFunction can be invoked multiple times per element within the array. Depending on the compareFunction's nature, this may yield a high overhead. The more work a compareFunction does and the more elements there are to sort, the wiser it may be to consider using a map for sorting. The idea is to walk the array once to extract the actual values used for sorting into a temporary array, sort the temporary array and then walk the temporary array to achieve the right order.

+ +
// the array to be sorted
+var list = ['Delta', 'alpha', 'CHARLIE', 'bravo'];
+
+// temporary array holds objects with position and sort-value
+var mapped = list.map(function(el, i) {
+  return { index: i, value: el.toLowerCase() };
+})
+
+// sorting the mapped array containing the reduced values
+mapped.sort(function(a, b) {
+  return +(a.value > b.value) || +(a.value === b.value) - 1;
+});
+
+// container for the resulting order
+var result = mapped.map(function(el){
+  return list[el.index];
+});
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition.
{{SpecName('ES5.1', '#sec-15.4.4.11', 'Array.prototype.sort')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-array.prototype.sort', 'Array.prototype.sort')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-array.prototype.sort', 'Array.prototype.sort')}}{{Spec2('ESDraft')}}
+ +

Böngésző kompatibilitás

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FunkcióChromeFirefox (Gecko)Internet ExplorerOperaSafari
Alap támogatás{{CompatChrome("1.0")}}{{CompatGeckoDesktop("1.7")}}{{CompatIE("5.5")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FunkcióAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Alap támogátás{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Lásd még

+ + diff --git a/files/hu/web/javascript/reference/global_objects/error/index.html b/files/hu/web/javascript/reference/global_objects/error/index.html new file mode 100644 index 0000000000..f27374e30c --- /dev/null +++ b/files/hu/web/javascript/reference/global_objects/error/index.html @@ -0,0 +1,218 @@ +--- +title: Error +slug: Web/JavaScript/Reference/Global_Objects/Error +translation_of: Web/JavaScript/Reference/Global_Objects/Error +--- +
{{JSRef}}
+ +

Az Error objektumok futásidejű hiba során keletkeznek. Továbbá ezek az alapjai a saját készítésű hibaobjektumoknak is. Később olvashatsz a beépített hiba típusokról is.

+ +

Leírás

+ +

A futásidejű hibák során Error objektumok keletkezhetnek, illetve érkezhetnek.

+ +

Hiba típusok

+ +

A generikus Error konstruktor mellett, A JavaScript-ben más hiba konstruktorok is léteznek. A kliens-oldali kivételek listájához, lásd, a Kivételek kezelése fejezetet.

+ +
+
{{JSxRef("EvalError")}}
+
Egy olyan hibaobjektum példányát hozza létre, ami az {{JSxRef("eval", "eval()")}} globális függvénnyel kapcsolatos.
+
{{JSxRef("RangeError")}}
+
Egy olyan hibaobjektum példányát hozza létre, ami akkor történik, ha valamelyik szám típusú változó az érvényes értékkészleten kívűlre esik.
+
{{JSxRef("ReferenceError")}}
+
Egy olyan hibaobjektum példányát hozza létre, ami akkor történik, ha érvénytelen hivatkozásra történik hivatkozás.
+
{{JSxRef("SyntaxError")}}
+
Egy olyan hibaobjektum példányát hozza létre, ami egy szintaktikai hibát jelez.
+
{{JSxRef("TypeError")}}
+
Egy olyan hibaobjektum példányát hozza létre, ami akkor keletkezik, ha a változó, vagy paraméter típusa nem megfelelő, vagy érvénytelen.
+
{{JSxRef("URIError")}}
+
Egy olyan hibaobjektum példányát hozza létre, ami akkor keletkezik, ha az {{JSxRef("encodeURI", "encodeURI()")}}, vagy a {{JSxRef("decodeURI", "decodeURI()")}} függvények érvénytelen bemeneti paramétereket kapnak.
+
{{JSxRef("AggregateError")}}
+
Egy olyan hibaobjektum példányát hozza létre, ami egyszerre több hibát foglal magába. Ilyen objektum akkor jön létre, amikor egy függvényben egyidejűleg több hiba is történik. Például.: {{JSxRef("Promise.any()")}}.
+
{{JSxRef("InternalError")}} {{non-standard_inline}}
+
Egy olyan hibaobjektum példányát hozza létre, ami akkor jön létre, amikor a JavaScript motorjában belső hiba keletkezik. Pl.: "too much recursion" ("Túl sok rekurzió").
+
+ +

Konstruktor

+ +
+
Error()
+
Egy új Error objektumot hoz létre.
+
+ +

Statikus függvények

+ +
+
{{JSxRef("Error.captureStackTrace()")}}
+
Egy nem-standard V8 függvény, ami létrehoz egy {{JSxRef("Error.prototype.stack", "stack")}} tagváltozót az Error példányon.
+
+ +

Példány tagváltozói

+ +
+
{{jsxref("Error.prototype.message")}}
+
Rövid hibaüzenet.
+
{{jsxref("Error.prototype.name")}}
+
A hiba neve.
+
{{jsxref("Error.prototype.description")}}
+
Egy nem-standard Microsoft tagváltozó a hiba leírásához. Hasonlít a {{jsxref("Error.prototype.message", "message")}}-hez.
+
{{jsxref("Error.prototype.number")}}
+
Egy nem-standard Microsoft tagváltozó a hiba számához.
+
{{jsxref("Error.prototype.fileName")}}
+
Egy nem-standard Mozilla tagváltozó, ami a hibát okozó fájl útvonalát tartalmazza.
+
{{jsxref("Error.prototype.lineNumber")}}
+
Egy nem-standard Mozilla tagváltozó, ami a hibát okozó fájl azon sorát jelöli, ahonnan a hiba származik.
+
{{jsxref("Error.prototype.columnNumber")}}
+
Egy nem-standard Mozilla tagváltozó, ami a hibát tartalmazó sor azon oszlopát (karakterét) jelöli, ahonnan a hiba származik.
+
{{jsxref("Error.prototype.stack")}}
+
Egy nem-standard Mozilla tagváltozó ami a stacktrace-t tartalmazza (A hiba nyomonkövetése a veremen).
+
+ +

Példány függvények

+ +
+
{{jsxref("Error.prototype.toString()")}}
+
Egy string-gel tér vissza, ami leírja az objektumot. Ez a függvény felüldefiniálja a {{jsxref("Object.prototype.toString()")}} fügvényt.
+
+ +

Példák

+ +

Generikus hiba keletkezése

+ +

Az Error objektumot általában akkor érdemes létrehozni, ha azt utána használjuk, vagy eldobjuk a {{JSxRef("Statements/throw", "throw")}} kulcsszó segítségével. Az ilyen hibákat a {{JSxRef("Statements/try...catch", "try...catch")}} szerkezettel lehet könnyedén kezelni:

+ +
try {
+  throw new Error('Whoops!')
+} catch (e) {
+  console.error(e.name + ': ' + e.message)
+}
+
+ +

Különleges hibák kezelése

+ +

A hiba objektum {{JSxRef("Object.prototype.constructor", "constructor")}} tagváltozójával, illetve modern JavaScript motor használata esetén, a {{JSxRef("Operators/instanceof", "instanceof")}} kulcsszóval lehetséges a hiba objektum konkrét típusát is lekérdezni. Ezzel leszűkíthető a hibakezelés konkrét hibatípusokra:

+ +
try {
+  foo.bar()
+} catch (e) {
+  if (e instanceof EvalError) {
+    console.error(e.name + ': ' + e.message)
+  } else if (e instanceof RangeError) {
+    console.error(e.name + ': ' + e.message)
+  }
+  // ... etc
+}
+
+ +

Saját hiba típusok

+ +

Elképzelhető, hogy saját hibatípust szereténk készíteni, ami az Error objektumból származik. Ezáltal tudjuk használni a throw new MyError() kifejezést a hiba jelzéséhez, és az instanceof MyError -t a különleges hiba kezeléséhez. Ezzel biztosítható a szebb és konzisztensebb hibakezelés. 

+ +

A kérdéskörről olvashatsz bővebben a "What's a good way to extend Error in JavaScript?" című téma alatt a StackOverflow fórumán.

+ +

ES6 Saját Error Osztály

+ +
+

7-es, vagy régebbi Babel verziók képesek a CustomError osztályfüggvények kezelésére, de csak akkor, ha azokat at Object.defineProperty()-vel megfelelően deklarálták. Máskülönben, a Babel régebbi verziói és más fordítók nem tudják kezelni az alábbi kódrészletet hozzáadott konfiguráció nélkül.

+
+ +
+

Egyes böngészőkben előfordul a CustomError konstruktor a stacktrace-ben, ha ES2015-ös osztályokat használunk.

+
+ +
class CustomError extends Error {
+  constructor(foo = 'bar', ...params) {
+    // Pass remaining arguments (including vendor specific ones) to parent constructor
+    super(...params)
+
+    // Maintains proper stack trace for where our error was thrown (only available on V8)
+    if (Error.captureStackTrace) {
+      Error.captureStackTrace(this, CustomError)
+    }
+
+    this.name = 'CustomError'
+    // Custom debugging information
+    this.foo = foo
+    this.date = new Date()
+  }
+}
+
+try {
+  throw new CustomError('baz', 'bazMessage')
+} catch(e) {
+  console.error(e.name)    //CustomError
+  console.error(e.foo)     //baz
+  console.error(e.message) //bazMessage
+  console.error(e.stack)   //stacktrace
+}
+ +

ES5 Saját Error Objektumok

+ +
+

Minden böngészőben előfordul a CustomError konstruktor a stacktrace-ben, ha prototípus alapján deklaráljuk azt.

+
+ +
function CustomError(foo, message, fileName, lineNumber) {
+  var instance = new Error(message, fileName, lineNumber);
+  instance.name = 'CustomError';
+  instance.foo = foo;
+  Object.setPrototypeOf(instance, Object.getPrototypeOf(this));
+  if (Error.captureStackTrace) {
+    Error.captureStackTrace(instance, CustomError);
+  }
+  return instance;
+}
+
+CustomError.prototype = Object.create(Error.prototype, {
+  constructor: {
+    value: Error,
+    enumerable: false,
+    writable: true,
+    configurable: true
+  }
+});
+
+if (Object.setPrototypeOf){
+  Object.setPrototypeOf(CustomError, Error);
+} else {
+  CustomError.__proto__ = Error;
+}
+
+try {
+  throw new CustomError('baz', 'bazMessage');
+} catch(e){
+  console.error(e.name); //CustomError
+  console.error(e.foo); //baz
+  console.error(e.message); //bazMessage
+}
+ +

Specifikációk

+ + + + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-error-objects', 'Error')}}
+ +

Böngészőkompatibilitás

+ +
+ + +

{{Compat("javascript.builtins.Error")}}

+
+ +

Lásd még

+ + diff --git "a/files/hu/web/javascript/reference/global_objects/f\303\274ggv\303\251ny/index.html" "b/files/hu/web/javascript/reference/global_objects/f\303\274ggv\303\251ny/index.html" new file mode 100644 index 0000000000..2e1f19b7c6 --- /dev/null +++ "b/files/hu/web/javascript/reference/global_objects/f\303\274ggv\303\251ny/index.html" @@ -0,0 +1,112 @@ +--- +title: Függvény +slug: Web/JavaScript/Reference/Global_Objects/Függvény +tags: + - Függvény + - JavaScript + - Osztály +translation_of: Web/JavaScript/Reference/Global_Objects/Function +--- +
{{JSRef}}
+ +

Minden JavaScript függvény tulajdonképpen egy Function objektum. Ez látható a következő kódnál, amely igazat ad vissza: (function(){}).constructor === Function.

+ +

Konstruktor

+ +
+
{{jsxref("Function/Function", "Function()")}}
+
Létrehoz egy új Function objektumot. A konstruktor közvetlen meghívásával dinamikusan hozhatók létre függvények, de ez biztonsági és az {{jsxref("eval")}}hoz hasonló (de sokkal kevésbé jelentős) teljesítménybeli problémáktól szenved. Viszont, az evaltól ellentétben, a Function konstruktor olyan függvényeket hoz létre, melyek mindig a globális hatókörben hajtódnak végre.
+
+ +

Példánytulajdonságok

+ +
+
{{jsxref("Function.arguments")}}
+
A függvénynek átadott argumentumokból álló tömb.
+ A {{jsxref("Function")}} elavult tulajdonsága. Helyette az {{jsxref("Functions/arguments", "arguments")}} objektum (a függvényen belül érhető el) használandó.
+
{{jsxref("Function.caller")}}
+
A jelenleg futó függvényt meghívó függvényt adja meg.
+ Ez a tulajdonság elavult, és csak egyes nem szigorú függvényekben működik.
+
{{jsxref("Function.displayName")}}
+
A függvény megjelenítendő neve.
+
{{jsxref("Function.length")}}
+
Megadja a függvény által várt argumentumok számát.
+
{{jsxref("Function.name")}}
+
A függvény neve.
+
+ +

Példánymetódusok

+ +
+
{{jsxref("Function.prototype.apply()", "Function.prototype.apply(thisArg [, argsArray])")}}
+
Meghív egy függvényt, és beállítja a this értékét a megadott thisArg értékre. Az argumentumok {{jsxref("Array")}} objektumként adhatók át.
+
{{jsxref("Function.prototype.bind()", "Function.prototype.bind(thisArg[, arg1[, arg2[, ...argN]]])")}}
+
Létrehoz egy új függvényt, amely meghívásakor beállítja a this értékét a megadott thisArg értékre. Az opcionálisan megadható argumentumsor az új függvény meghívásakor átadott argumentumok elé lesz fűzve.
+
{{jsxref("Function.prototype.call()", "Function.prototype.call(thisArg[, arg1, arg2, ...argN])")}}
+
Meghív egy függvényt, és beállítja a this értékét a megadott értékre. Az argumentumok egyszerűen átadhatók.
+
{{jsxref("Function.prototype.toString()", "Function.prototype.toString()")}}
+
Visszaadja a függvény forráskódját ábrázáló karakterláncot.
+ Felülírja a {{jsxref("Object.prototype.toString")}} metódust.
+
+ +

Példák

+ +

Különbség a Function konstruktor és a függvénydeklaráció között

+ +

A Function konstruktorral létrehozott függvények nem hoznak létre zárványt a létrehozási környezetükhöz, mindig a globális hatókörbe kerülnek. Futtatáskor csak a saját helyi változóit és a globálisakat éri el, a Function konstruktor meghívásakor aktív hatókörben szereplőket nem. Ez különbözik az {{jsxref("eval")}} függvénykifejezésen történő használatától.

+ +
var x = 10;
+
+function createFunction1() {
+    var x = 20;
+    return new Function('return x;'); // az |x| a globális |x|-et jelenti
+}
+
+function createFunction2() {
+    var x = 20;
+    function f() {
+        return x; // ez az |x| a fent lévő helyi |x|-et jelenti
+    }
+    return f;
+}
+
+var f1 = createFunction1();
+console.log(f1());          // 10
+var f2 = createFunction2();
+console.log(f2());          // 20
+
+ +

A kód működik a webböngészőkben, de az f1() ReferenceError hibát okoz Node.js-ben, mert az x nem található. Ez azért van, mert a Node legfelső szintű hatóköre nincs a globális hatókörben, és az x a modulra nézve helyi változó lesz.

+ +

Specifikációk

+ + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-function-objects', 'Function')}}
+ +

Böngészőkompatibilitás

+ +
+ + +

{{Compat("javascript.builtins.Function")}}

+
+ +

Lásd még:

+ + diff --git a/files/hu/web/javascript/reference/global_objects/index.html b/files/hu/web/javascript/reference/global_objects/index.html new file mode 100644 index 0000000000..10b4e99123 --- /dev/null +++ b/files/hu/web/javascript/reference/global_objects/index.html @@ -0,0 +1,192 @@ +--- +title: Standard built-in objects +slug: Web/JavaScript/Reference/Global_Objects +tags: + - JavaScript + - NeedsTranslation + - Reference + - TopicStub +translation_of: Web/JavaScript/Reference/Global_Objects +--- +
{{jsSidebar("Objects")}}
+ +

This chapter documents all of JavaScript's standard, built-in objects, including their methods and properties.

+ +
+

The term "global objects" (or standard built-in objects) here is not to be confused with the global object. Here, global objects refer to objects in the global scope (but only if ECMAScript 5 strict mode is not used; in that case it returns {{jsxref("undefined")}}). The global object itself can be accessed using the {{jsxref("Operators/this", "this")}} operator in the global scope. In fact, the global scope consists of the properties of the global object, including inherited properties, if any.

+ +

Other objects in the global scope are either created by the user script or provided by the host application. The host objects available in browser contexts are documented in the API reference. For more information about the distinction between the DOM and core JavaScript, see JavaScript technologies overview.

+ +

Standard objects by category

+ +

Value properties

+ +

These global properties return a simple value; they have no properties or methods.

+ + + +

Function properties

+ +

These global functions—functions which are called globally rather than on an object—directly return their results to the caller.

+ + + +

Fundamental objects

+ +

These are the fundamental, basic objects upon which all other objects are based. This includes objects that represent general objects, functions, and errors.

+ + + +

Numbers and dates

+ +

These are the base objects representing numbers, dates, and mathematical calculations.

+ + + +

Text processing

+ +

These objects represent strings and support manipulating them.

+ + + +

Indexed collections

+ +

These objects represent collections of data which are ordered by an index value. This includes (typed) arrays and array-like constructs.

+ + + +

Keyed collections

+ +

These objects represent collections which use keys; these contain elements which are iterable in the order of insertion.

+ + + +

Vector collections

+ +

{{Glossary("SIMD")}} vector data types are objects where data is arranged into lanes.

+ + + +

Structured data

+ +

These objects represent and interact with structured data buffers and data coded using JavaScript Object Notation (JSON).

+ + + +

Control abstraction objects

+ + + +

Reflection

+ + + +

Internationalization

+ +

Additions to the ECMAScript core for language-sensitive functionalities.

+ + + +

Non-standard objects

+ + + +

Other

+ + +
+ +

 

diff --git a/files/hu/web/javascript/reference/global_objects/nan/index.html b/files/hu/web/javascript/reference/global_objects/nan/index.html new file mode 100644 index 0000000000..16d2c13c79 --- /dev/null +++ b/files/hu/web/javascript/reference/global_objects/nan/index.html @@ -0,0 +1,96 @@ +--- +title: NaN +slug: Web/JavaScript/Reference/Global_Objects/NaN +tags: + - JavaScript + - NaN + - Referencia + - Változó +translation_of: Web/JavaScript/Reference/Global_Objects/NaN +--- +
{{jsSidebar("Objects")}}
+ +

A globális NaN egy olyan változó, ami a Not-A-Number típusú értéket reprezentálja.

+ +

{{js_property_attributes(0,0,0)}}

+ +
{{EmbedInteractiveExample("pages/js/globalprops-nan.html")}}
+ + + +

Leírás

+ +

A NaN a globális objektum része. Más szavakkal a globális scope egyik változója.

+ +

A NaN eredeti jelentése: Not-A-Number (nem szám). Értéke a {{jsxref("Number.NaN")}}-nal egyenlő. Modern böngészőkben a NaN nem beállítható, nem írható változó. Ellenkező esetben sem tanácsolt felüldefiniálni. A NaN közvetlen használata egy programban igen ritka.

+ +

Öt különböző típusú műveletet különböztethetünk meg, aminek az eredménye NaN:

+ + + +

Példák

+ +

Tesztelés NaN esetre

+ +

NaN nem összehasonlítható (az ==, !=, ===, és !== operátorokkal) semmilyen más értékkel. -- beleértve magát a NaN értéket. Ahhoz, hogy valamiről biztosan eldöntsük, hogy NaN a {{jsxref("Number.isNaN()")}}, illetve a {{jsxref("Global_Objects/isNaN", "isNaN()")}} függvényeket használhatjuk. Alternatívaként összehasonlíthatjuk a változót saját magával, mert a NaN, és csak is a NaN az az érték, ami nem egyenlő önmagával.

+ +
NaN === NaN;        // false
+Number.NaN === NaN; // false
+isNaN(NaN);         // true
+isNaN(Number.NaN);  // true
+Number.isNaN(NaN);  // true
+
+function valueIsNaN(v) { return v !== v; }
+valueIsNaN(1);          // false
+valueIsNaN(NaN);        // true
+valueIsNaN(Number.NaN); // true
+
+ +

Fontos felhívni a figyelmet az isNaN() és a Number.isNaN() közötti különbséget: míg az előbbi true-val tér vissza akkor is, ha az érték éppen NaN, és akkor is ha az a kiértékelés után NaN-ná válik, úgy az utóbbi csak akkor tér vissza true-val, ha az érték éppen NaN:

+ +
isNaN('hello world');        // true
+Number.isNaN('hello world'); // false
+
+ +

Továbbá, bizonyos tömbfüggvények nem használhatók a NaN keresésére, míg vannak, amik igen.

+ +
let arr = [2, 4, NaN, 12];
+arr.indexOf(NaN);                      // -1 (false)
+arr.includes(NaN);                     // true
+arr.findIndex(n => Number.isNaN(n));   // 2
+
+ +

Specifikáció

+ + + + + + + + + + + + +
Specifikáció
{{SpecName('ESDraft', '#sec-value-properties-of-the-global-object-nan', 'NaN')}}
+ +

Böngésző kompatibilitás

+ + + +

{{Compat("javascript.builtins.NaN")}}

+ +

Lásd még

+ + diff --git a/files/hu/web/javascript/reference/global_objects/string/index.html b/files/hu/web/javascript/reference/global_objects/string/index.html new file mode 100644 index 0000000000..4f91f13008 --- /dev/null +++ b/files/hu/web/javascript/reference/global_objects/string/index.html @@ -0,0 +1,307 @@ +--- +title: String +slug: Web/JavaScript/Reference/Global_Objects/String +tags: + - húzáskérvény +translation_of: Web/JavaScript/Reference/Global_Objects/String +--- +
{{JSRef}}
+ +

A String konstruktorral létrehozhatunk karakterláncokat (szövegek szinte mindenhol jelenlévő reprezentációja)

+ +

Szintaxis

+ +

A sztringliterálok a következő formájúak:

+ +
'sztring szöveg'
+"sztring szöveg"
+"中文 español Deutsch English देवनागरी العربية português বাংলা русский 日本語 norsk bokmål ਪੰਜਾਬੀ 한국어 தமிழ் עברית"
+ +

Sztringeket létrehozhatunk a String globális objektummal közvetlenül:

+ +
String(valami)
+ +

Paraméterek

+ +
+
valami
+
Bármi, ami sztringgé alakítható.
+
+ +

Sablon literálok

+ +

Az ECMAScript 2015-tel kezdődően, a sztringliterálok ún. Template literal-ok is lehetnek:

+ +
`hello világ`
+`hello!
+ world!`
+`hello ${who}`
+tag `<a>${who}</a>`
+ +

Itt a ${who} helyére a megfelelő érték fog behelyettsítődni.

+ +

Escape jelölés

+ +

Egyes karakterek összezavarhatnák a JavaScript értelmezőt. Például egy " karakterről hogyan tufná megállapítani, hogy a karakterlánc végét jelöli, vagy annak része? Erre találták ki az escape jelölést, aminek segítségével jelölhetjük, hogy egy karakternek nincs speciális szerepe, nem kell programkódként értelmezni. Lényegében az történik, hogy a feldolgozott karakterláncban az escape karakter (például a \") helyére az annak megfelelő kimenet (") kerül.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
KódKimenet
\XXXoktális Latin-1 karakter.
\'egyszeres idézőjel
\"idézőjel
\\backslash
\núj sor (soremelés)
\rkocsi-vissza
\vfüggőleges tabulátor
\ttabulátor
\bbackspace
\flapdobás
\uXXXXunicode kódpont
\u{X} ... \u{XXXXXX}unicode kódpont {{experimental_inline}}
\xXXhexadecimális Latin-1 karakter
+ +
+

Más nyelvekkel ellentétben a JavaScript nem különbözteti meg az egyszeres, illetve a kettős idézőjelekkel hivatkozott sztringeket; ezért a fenti escape szekvenciák mind az egyszeres, mind a kettős idézőjelekkel létrehozott sztringek esetén működnek.

+
+ +

Hosszú sztring literálok

+ +

Időnként a kódban szerepelhetnek nagyon hosszú sztringek. Vég nélkül folytatódó, illetve a szerkesztőprogram kénye-kedve szerint megtört sorok helyett lehetséges a sztringek több sorba tördelése a tartalom meghagyásával. Erre két mód van.

+ +

Használhatjuk a + operátort több füzér összefűzéséhez, így:

+ +
let longString = "Ez egy elég hosszú String ahhoz " +
+                 "hogy több sorba rendezzem, mert " +
+                 "máskülönben a kód nem olvasható.";
+
+ +

Vagy használható a backslash karakter ("\") az összes sor végén, jelölve, hogy a sztring a következő sorban folytatódik. Győződjünk meg róla, hogy nincs szóköz vagy más karakter a backslash után (soremelés kivételével), akár bekezdésként, különben nem fog működni. Ennek formája a kövekező:

+ +
let longString = "This is a very long string which needs \
+to wrap across multiple lines because \
+otherwise my code is unreadable.";
+
+ +

Mindkét forma a példában azonos sztringek létrehozását eredményezi.

+ +

Leírás

+ +

A stringek szöveges formában ábrázolt adatok tárolására használhatók. A leggyakoribb sztringműveletek közé tartozik a {{jsxref("String.length", "hossz")}} vizsgálata, azok felépítése és összefűzése a + és += sztring operátorokkal, alfüzérek meglétének és helyének vizsgálata a {{jsxref("String.prototype.indexOf()", "indexOf()")}} metódussal, illetve alfüzérek lekérdezése a {{jsxref("String.prototype.substring()", "substring()")}} metódussal.

+ +

Karakter hozzáférés

+ +

Kétféle mód van egy sztringben az egyes karakterekhez vakó hozzáféréshez. Az egyik a {{jsxref("String.prototype.charAt()", "charAt()")}} metódus:

+ +
return 'macska'.charAt(1); // "a"-val tér vissza
+
+ +

A másik mód (bevezetve az ECMAScript 5-ben) tömbszerű objektumként kezeli a sztringet, ahol az egyes karaktereknem számindexek felelnek meg:

+ +
return 'macska'[1]; // "a"-val tér vissza
+
+ +

Törölni vagy megváltoztatni e tulajdonságokat karakter hozzáféréssel nem lehet a szögletes zárójeles jelölés esetén. A szóban forgó tulajdonságok nem írhatók és nem is konfigurálhatók. (Lásd a {{jsxref("Object.defineProperty()")}} cikket további információért.)

+ +

Sztringek összehasonlítása

+ +

C fejlesztőknek ismerős lehet a strcmp() függvény sztringek összehasonlításához. A JavaScript-ben a kisebb és nagyobb operátorok használhatók:

+ +
var a = 'a';
+var b = 'b';
+if (a < b) { // true
+  console.log(a + ' kisebb, mint ' + b);
+} else if (a > b) {
+  console.log(a + ' nagyobb, mint ' + b);
+} else {
+  console.log(a + ' és ' + b + ' egyenlők.');
+}
+
+ +

Hasonlót eredményez a {{jsxref("String.prototype.localeCompare()", "localeCompare()")}} metódus, amelyet a String példányok örökölnek.

+ +

Sztring primitívek és String objektumok megkülönböztetése

+ +

Jegyezzük meg, hogy a JavaScript különbséget tesz String objektumok és primitív sztring értékek között. (Ugyanez igaz {{jsxref("Boolean")}} és {{jsxref("Global_Objects/Number", "Number")}} objektumokra.)

+ +

Sztringliterálok (egyszeri vagy kettős idézőjellel jelölve) és a String hívásából visszatérő, nem konstruktor kontextusból (azaz, nem a {{jsxref("Operators/new", "new")}} kulcsszó használatával) kapott sztringek primitív sztringek. A JavaScript automatikusan String objektumokká alakítja a primitíveket, hogy eképpen a String objektum metódusai primitív sztringeken is használhatók legyenek. Amikor primitív sztringen hívódik metódus vagy tulajdonság lekérdezés, a JavaScript automatikusan String objektummá alakítja a sztringet és így hívja meg a metódust, illetve a lekérdezést.

+ +
var s_prim = 'foo';
+var s_obj = new String(s_prim);
+
+console.log(typeof s_prim); // Konzol kimenet: "string"
+console.log(typeof s_obj);  // Konzol kimenet: "object"
+
+ +

Sztring primitívek és String objektumok az {{jsxref("Global_Objects/eval", "eval()")}} használatakor is különböző eredményt adnak. Az eval számára átadott primitívek forráskódként vannak kezelve, míg a String objektumok, mint bármely más átadott objektum esetén, az objektum visszaadását eredményezik. Például:

+ +
var s1 = '2 + 2';             // létrehoz egy sztring primitívet
+var s2 = new String('2 + 2'); // létrehoz egy String objektumot
+console.log(eval(s1));        // a 4 számmal tér vissza
+console.log(eval(s2));        // a "2 + 2" sztringgel tér vissza
+
+ +

Ezen okok miatt a kód hibás működését okozhatja, amikor String a kód String objektumot kap, miközben primitív sztringet vár, bár általában nem szükséges a fejlesztőknek ezzel törődni.

+ +

Egy String objektum mindig átalakítható a primitív megfelelőjére a  {{jsxref("String.prototype.valueOf()", "valueOf()")}} metódussal.

+ +
console.log(eval(s2.valueOf())); // 4-et ad vissza
+
+ +
Megjegyzés: Egy másik JavaScript-ben lehetséges megközelítésére a sztringeknek, lásd a StringView — a C-like representation of strings based on typed arrays cikket.
+ +

Tulajdonságok

+ +
+
{{jsxref("String.prototype")}}
+
Tulajdonságok hozzáadását engedélyezi egy String objektumhoz.
+
+ +

Metódusok

+ +
+
{{jsxref("String.fromCharCode()")}}
+
Unicode értékek meghatározott sorozatával megadott sztringgel tér vissza.
+
{{jsxref("String.fromCodePoint()")}}
+
Kódpontok meghatározott sorozatával megadott sztringgel tér vissza.
+
{{jsxref("String.raw()")}} {{experimental_inline}}
+
Nyers sablon sztring szerint létrehozott sztringgel tér vissza.
+
+ +

String generikus metódusok

+ +
+

A String generikusok nem szabványosak, elavultak és a közeljövőben törlésre kerülnek.

+
+ +

String példánymetódusok a JavaScript 1.6 óta elérhetők Firefox-ban (nem része az ECMAScript szabványnak) a String objektumon bármely objektumon String metódusok alkalmazására:

+ +
var num = 15;
+console.log(String.replace(num, "5", "2"));
+
+ +

A String generikusokról való áttéréshez lásd a Warning: String.x is deprecated; use String.prototype.x instead cikket.

+ +

Tömbök generikusai ({{jsxref("Global_Objects/Array", "Generics", "#Array_generic_methods", 1)}}) a tömb ({{jsxref("Array")}}) metódusokra is elérhetők.

+ +

String példányok

+ +

Tulajdonságok

+ +
{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/prototype', 'Tulajdonságok')}}
+ +

Metódusok

+ +

HTML-hez nem kapcsolódó metódusok

+ +
{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/prototype', 'Methods_unrelated_to_HTML')}}
+ +

HTML wrapper methods

+ +
{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/prototype', 'HTML_wrapper_methods')}}
+ +

Példák

+ +

String konverzió

+ +

A String használható egy biztonságosabb {{jsxref("String.prototype.toString()", "toString()")}} alternatívaként, mivel {{jsxref("null")}}, {{jsxref("undefined")}}, és {{jsxref("Symbol", "symbol")}} objektumokra is használható. Például:

+ +
var outputStrings = [];
+for (var i = 0, n = inputValues.length; i < n; ++i) {
+  outputStrings.push(String(inputValues[i]));
+}
+
+ +

Specifikációk

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificációStátuszMegjegyzés
{{SpecName('ESDraft', '#sec-string-objects', 'String')}}{{Spec2('ESDraft')}}
{{SpecName('ES2015', '#sec-string-objects', 'String')}}{{Spec2('ES2015')}}
{{SpecName('ES5.1', '#sec-15.5', 'String')}}{{Spec2('ES5.1')}}
{{SpecName('ES1')}}{{Spec2('ES1')}}Kezdeti definíció.
+ +

Böngésző kompatibilitás

+ + + +

{{Compat("javascript.builtins.String",2)}}

+ +

Lásd még

+ + diff --git a/files/hu/web/javascript/reference/index.html b/files/hu/web/javascript/reference/index.html new file mode 100644 index 0000000000..08006f6ab5 --- /dev/null +++ b/files/hu/web/javascript/reference/index.html @@ -0,0 +1,197 @@ +--- +title: JavaScript reference +slug: Web/JavaScript/Reference +tags: + - JavaScript + - NeedsTranslation + - TopicStub +translation_of: Web/JavaScript/Reference +--- +
{{JsSidebar}}
+ +

Ez a része a JavaScript szekciónak ténylek tárolójaként szolgál a JavaScript nyelvről az MDN szerverein. Olvass tovább erről a hivatkozásról.

+ +

Globális objektumok

+ +

Ez a fejezet dokumentálja a JavaScript összes szabványos, beépített objektumait, a metódusaikkal és tulajdonságaikkal együtt.

+ +
{{page('/hu/docs/Web/JavaScript/Reference/Global_Objects', 'Standard objects (by category)')}}
+ +
+ +
+

Értéket kifejező objektumok

+ + + +

Függvény objektumok

+ + + +

Alapvető objektumok

+ + + +

Hiba objektumok

+ + + +

Számok és Dátumok

+ + + +

Szövegkezelés

+ + + +

Számozott gyűjtemények (tömbök)

+ + + +

Referált gyűjtemények (leképezések)

+ + + +

Adatstruktúrák

+ + + +

Control absztrakció

+ + + +

Reflexió

+ + + +

Nemzetközi szabványok

+ + + +

Webfejlesztés

+ + +
+ +

Utasítások

+ +

Ez a fejezet dokumentálja az összes JavaScript utasítást és deklarációt.

+ +
{{page('/en-US/docs/Web/JavaScript/Reference/Statements', 'Statements_and_declarations_by_category')}}
+ +

Kifejezések és operátorok

+ +

Ez a fejezet dokumentálja az összes JavaScript kifejezést és operátort.

+ +
{{page('/en-US/docs/Web/JavaScript/Reference/Operators', 'Expressions_and_operators_by_category')}}
+ +

Függvények

+ +

Ezen fejezet dokumentációja megmutatja, hogyan dolgozz JavaScript függvényekkel a saját alkalmazásaid fejlesztéséhez.

+ + + +

További referencia oldalak

+ + diff --git a/files/hu/web/javascript/reference/statements/index.html b/files/hu/web/javascript/reference/statements/index.html new file mode 100644 index 0000000000..368977efc8 --- /dev/null +++ b/files/hu/web/javascript/reference/statements/index.html @@ -0,0 +1,131 @@ +--- +title: Statements and declarations +slug: Web/JavaScript/Reference/Statements +tags: + - JavaScript + - NeedsTranslation + - Reference + - TopicStub + - statements +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.
+
{{experimental_inline}} {{jsxref("Statements/let", "let")}}
+
Declares a block scope local variable, optionally initializing it to a value.
+
{{experimental_inline}} {{jsxref("Statements/const", "const")}}
+
Declares a read-only named constant.
+
+ +

Functions and classes

+ +
+
{{jsxref("Statements/function", "function")}}
+
Declares a function with the specified parameters.
+
{{experimental_inline}} {{jsxref("Statements/function*", "function*")}}
+
Generators functions enable writing iterators more easily.
+
{{jsxref("Statements/return", "return")}}
+
Specifies the value to be returned by a function.
+
{{experimental_inline}} {{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.
+
{{experimental_inline}} {{jsxref("Statements/for...of", "for...of")}}
+
Iterates over iterable objects (including arrays, 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.
+
{{experimental_inline}} {{jsxref("Statements/export", "export")}}
+
Used to export functions to make them available for imports in external modules, another scripts.
+
{{experimental_inline}} {{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
ECMAScript 1st Edition.StandardInitial definition.
{{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
+ +

See also

+ + diff --git a/files/hu/web/javascript/reference/statements/try...catch/index.html b/files/hu/web/javascript/reference/statements/try...catch/index.html new file mode 100644 index 0000000000..4efd7b1278 --- /dev/null +++ b/files/hu/web/javascript/reference/statements/try...catch/index.html @@ -0,0 +1,321 @@ +--- +title: try...catch +slug: Web/JavaScript/Reference/Statements/try...catch +translation_of: Web/JavaScript/Reference/Statements/try...catch +--- +
{{jsSidebar("Statements")}}
+ +

try...catch szerkezet utasítások futtatására, majd a keletkező kivételek érzékelésére, kezelésére való.

+ +
{{EmbedInteractiveExample("pages/js/statement-trycatch.html")}}
+ +
Megjegyzés: ebben a cikkben a kivétel szó az angol szaknyelvi exception, blokk pedig a block vagy clause szó fordítása.
+ + + +

Szerkezet

+ +
try {
+   try_statements
+}
+[catch (exception_var_1 if condition_1) { // nem szabványos
+   catch_statements_1
+}]
+...
+[catch (exception_var_2) {
+   catch_statements_2
+}]
+[finally {
+   finally_statements
+}]
+ +
+
try_statements
+
Azok az utasítások, amelyek kivételt válthatnak ki.
+
+ +
+
catch_statements_1, catch_statements_2
+
Azok az utasítások, amelyek akkor hajtódnak végre, ha valami kivételt vált ki a try blokkban.
+
+ +
+
exception_var_1, exception_var_2
+
Annak a változónak a neve, amelyben az utána következő catch blokkban elérhető lesz a kivételobjektum (Exception).
+
+ +
+
condition_1
+
Valamilyen feltétel (mint egy if() kifejezésben).
+
+ +
+
finally_statements
+
Azok az utasítások, amelyeket a try blokk után le kell futtatni, tehát ezek attól függetlenül végrehajtódnak, hogy a try blokkban történt-e kivétel.
+
+ +

Kifejtés

+ +

A try szerkezetnek 3 megjelenési formája van:

+ +
    +
  1. try...catch
  2. +
  3. try...finally
  4. +
  5. try...catch...finally
  6. +
+ +

A try, a catch és a finally blokk egy vagy több utasításból állhat. A kapcsos zárójelek használata kötelező, még akkor is, ha egy utasításból áll csak a blokk. A try blokk után legalább egy catch vagy finally blokknak kell lennie.:

+ +

A catch blokk tartalmazza azokat az utasításokat, amelyek akkor hajtódnak végre, ha valami kivételt vált ki a try blokkban. Ha valami kivételt vált ki, a try blokk végrehajtása azonnal megszakad, és a catch blokk hajtódik végre. Ha nem történik kivétel, a catch blokk nem hajtódik végre.

+ +

A finally blokk végrehajtása a try és a catch blokk(ok) végrehajtása után, közvetlenül a blokk utáni utasítások előtt. Mindig végrehajtódik, attól függetlenül, hogy a try blokk sikeres volt-e.

+ +

A try szerkezetek egymásba ágyazhatóak. Ha egy beágyazott try blokkhoz nem tartozik catch blokk, az azt tartalmazó try blokkhoz tartozó catch/finally fog végrehajtódni.

+ +

A try szerkezettel a JavaScript kivételeit is lehet kezelni. További információ róluk: JavaScript Guide.

+ +

Feltétel nélküli catch blokk

+ +

Egyszerű, feltétel nélküli catch blokk esetén bármilyen kivétel váltódik ki, ugyanaz a blokk fog végrehajtódni. Például

+ +
try {
+   throw 'myException'; // generates an exception
+}
+catch (e) {
+   // statements to handle any exceptions
+   logMyErrors(e); // pass exception object to error handler
+}
+
+ +

A catch blokk használata során meg kell adnunk egy változónevet, ez a változó fogja tárolni a kivételobjektumot. A catch blokkban megadott változó élettartama eltér a szokásostól: a változó a catch blokk végrehajtása előtt jön létre, és a végrehajtás után nem elérhető.

+ +

Feltételes catch blokk

+ +

You can also use one or more conditional catch clauses to handle specific exceptions. In this case, the appropriate catch clause is entered when the specified exception is thrown. In the following example, code in the try block can potentially throw three exceptions: {{jsxref("TypeError")}}, {{jsxref("RangeError")}}, and {{jsxref("EvalError")}}. When an exception occurs, control transfers to the appropriate catch clause. If the exception is not one of the specified exceptions and an unconditional catch clause is found, control transfers to that catch clause.

+ +

If you use an unconditional catch clause with one or more conditional catch clauses, the unconditional catch clause must be specified last. Otherwise, the unconditional catch clause will intercept all types of exception before they can reach the conditional ones.

+ +

Emlékeztető: ez a lehetőség nem az ECMAScript szabvány része.

+ +
try {
+    myroutine(); // may throw three types of exceptions
+} catch (e if e instanceof TypeError) {
+    // statements to handle TypeError exceptions
+} catch (e if e instanceof RangeError) {
+    // statements to handle RangeError exceptions
+} catch (e if e instanceof EvalError) {
+    // statements to handle EvalError exceptions
+} catch (e) {
+    // statements to handle any unspecified exceptions
+    logMyErrors(e); // pass exception object to error handler
+}
+
+ +

Here is the same "Conditional catch clauses" using code that conforms to ECMAScript specification (obviously it's more verbose, but works everywhere):

+ +
try {
+    myroutine(); // may throw three types of exceptions
+} catch (e) {
+    if (e instanceof TypeError) {
+        // statements to handle TypeError exceptions
+    } else if (e instanceof RangeError) {
+        // statements to handle RangeError exceptions
+    } else if (e instanceof EvalError) {
+        // statements to handle EvalError exceptions
+    } else {
+       // statements to handle any unspecified exceptions
+       logMyErrors(e); // pass exception object to error handler
+    }
+}
+
+ +

The exception identifier

+ +

When an exception is thrown in the try block, exception_var (e.g. the e in catch (e)) holds the value specified by the throw statement. You can use this identifier to get information about the exception that was thrown. As of Firefox 58, when the exception is unused, the identifier can be omitted, as in

+ +
function isValidJSON(text) {
+    try {
+        JSON.parse(text);
+        return true;
+    } catch {
+        return false;
+    }
+}
+
+ +

This identifier is local to the catch clause. That is, it is created when the catch clause is entered, and after the catch clause finishes executing, the identifier is no longer available.

+ +

A finally blokk

+ +

A finally blokk azokat az utasításokat tartalmazza, amelyeket a catch blokk(ok) után, de a try-catch-finally szerkezet előtt kell végrehajtani. Mindenképpen végrehajtódik, attól függetlenül, hogy a try blokkban váltódott-e ki kivétel. A finally blokk megléte elfogadhatóvá teszi a catch blokk hiányát, de a kivételek megjelennek a blokkon kívül is. Amennyiben hiányzik a catch blokk, először a try-ban kiváltódott kivételek jelennek meg, majd ezután hajtódik végre a finally blokk.

+ +

A finally blokkot gyakran használják a program hiba esetén történő leállása előtti feladatok elvégzésére.

+ +

Enyhén szólva furcsának tűnhet, hogy a JavaScript kivételekhez kapcsolódó részében szerepel egy olyan ág is, ami attól függetlenül végrehajtódik, hogy váltódott-e ki kivétel. Ennek azomban, a látszattal ellentétben van értelme. A hangsúly nem azon van, hogy a finally blokk mindig végrehajtódik, hanem hogy az azt követő utasítások nem feltétlenül.

+ +

Például ha egy másik kivétel váltódik ki egy try-catch blokkon belül, semmilyen más kód ugyanabban a külső try-catch blokkban nem fog végrehajtódni.

+ +

For instance, if another exception occurs inside a try's catch-block, any remaining code in the same outer try-block enclosing that try..catch (or in the main flow, if not in an outer try-block) , will not get executed, since control is immediately transferred to the outer try's catch-block (or the internal error-generator, if not in a try-block).  

+ +

Thus, any routine cleanup code done in that enclosed (or the main) section before it exits, will be skipped.  However, If the try-block has a finally-block, then that finally-block code will be executed first to permit any such cleanup, and THEN the other try's catch-block (or the error-generator) will get control to handle the second exception.  

+ +

Now, if that routine cleanup must be done whether or not the try..catch code succeeds, then if the finally-block only executed after an exception, the same cleanup code would have to be duplicated both inside and outside the finally-block, and therefore there is no reason not to have just the finally-block alone, and let it execute regardless of exceptions or not.

+ +

The following example opens a file and then executes statements that use the file (server-side JavaScript allows you to access files). If an exception is thrown while the file is open, the finally clause closes the file before the script fails. The code in finally also executes upon explicitly returning from try or catch block.

+ +
openMyFile();
+try {
+   // tie up a resource
+   writeMyFile(theData);
+}
+finally {
+   closeMyFile(); // always close the resource
+}
+
+ +

Példák

+ +

Beágyazott try blokkok

+ +

Először is, nézzük meg ezt:

+ +
try {
+  try {
+    throw new Error('hoppácska');
+  }
+  finally {
+    console.log('finally blokk');
+  }
+}
+catch (ex) {
+  console.error('külső catch blokk', ex.message);
+}
+
+// Kimenet:
+// "finally blokk"
+// "külső catch blokk" "hoppácska"
+
+ +

Now, if we already caught the exception in the inner try-block by adding a catch block

+ +
try {
+  try {
+    throw new Error('hoppácska');
+  }
+  catch (ex) {
+    console.error('belső catch blokk', ex.message);
+  }
+  finally {
+    console.log('finally blokk');
+  }
+}
+catch (ex) {
+  console.error('outer', ex.message);
+}
+
+// Kimenet:
+// "belső catch blokk" "hoppácska"
+// "finally blokk"
+
+ +

Most pedig dobjuk tovább a kivételt:

+ +
try {
+  try {
+    throw new Error('hoppácska');
+  }
+  catch (ex) {
+    console.error('belső catck blokk', ex.message);
+    throw ex;
+  }
+  finally {
+    console.log('finally blokk');
+  }
+}
+catch (ex) {
+  console.error('külső catck blokk', ex.message);
+}
+
+// Output:
+// "belső catck blokk" "hoppácska"
+// "finally blokk"
+// "külső catck blokk" "hoppácska"
+
+ +

Minden kivételt csak a legközelebbi catch blokk fog elkapni, kivéve ha innen tovább dobjuk. Ez esetben a belső catch blokkból dobott kivételt a külső try-hez tartozó catch blokk fogja elkapni.

+ +

return használata a finally blokkban

+ +

Ha a finally blokk értéket ad vissza, ez az érték a teljes try-catch-finally szerkezet vissszatérési értékévé válik, a try és catch blokkokban lévő return utasításoktól függetlenül. Ebbe beletartoznak a catch blokkon belül dobott kivételek is.

+ +
(function() {
+  try {
+    try {
+      throw new Error('hoppácska');
+    }
+    catch (ex) {
+      console.error('belső catch blokk', ex.message);
+      throw ex;
+    }
+    finally {
+      console.log('finally blokk');
+      return;
+    }
+  }
+  catch (ex) {
+    console.error('külső', ex.message);
+  }
+})();
+
+// Kimenet:
+// "belső catch blokk" "hoppácska"
+// "finally blokk"
+ +

The outer "oops" is not thrown because of the return in the finally block. The same would apply to any value returned from the catch block.

+ +

Specifikációk

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecifikációStátuszMegjegyzés
{{SpecName('ES3')}}{{Spec2('ES3')}} +

Az első leírás. A JavaScript 1.4-ben lett megvalósítva.

+
{{SpecName('ES5.1', '#sec-12.14', 'try statement')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-try-statement', 'try statement')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-try-statement', 'try statement')}}{{Spec2('ESDraft')}}Nem része a jelenleg ECMA-262 szabványnak: Több catch blokk és feltételes bokkok (SpiderMonkey kiterjesztés, JavaScript 1.5).
+ +

Browser compatibility

+ + + +

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

+ +

See also

+ + -- cgit v1.2.3-54-g00ecf