From 037a4118c4324d39fdef8bd23f9dd21b02f50946 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Thu, 15 Jul 2021 13:01:50 -0400 Subject: delete pages that were never translated from en-US (pl, part 1) (#1549) --- files/pl/web/javascript/data_structures/index.html | 444 --------------------- .../deprecated_and_obsolete_features/index.html | 293 -------------- .../reference/global_objects/escape/index.html | 121 ------ .../reference/global_objects/generator/index.html | 179 --------- .../global_objects/string/blink/index.html | 51 --- .../global_objects/string/fromcodepoint/index.html | 148 ------- .../global_objects/string/repeat/index.html | 167 -------- .../global_objects/uint16array/index.html | 225 ----------- .../reference/operators/instanceof/index.html | 169 -------- .../javascript/reference/operators/this/index.html | 347 ---------------- .../reference/statements/throw/index.html | 198 --------- files/pl/web/javascript/typed_arrays/index.html | 274 ------------- 12 files changed, 2616 deletions(-) delete mode 100644 files/pl/web/javascript/data_structures/index.html delete mode 100644 files/pl/web/javascript/reference/deprecated_and_obsolete_features/index.html delete mode 100644 files/pl/web/javascript/reference/global_objects/escape/index.html delete mode 100644 files/pl/web/javascript/reference/global_objects/generator/index.html delete mode 100644 files/pl/web/javascript/reference/global_objects/string/blink/index.html delete mode 100644 files/pl/web/javascript/reference/global_objects/string/fromcodepoint/index.html delete mode 100644 files/pl/web/javascript/reference/global_objects/string/repeat/index.html delete mode 100644 files/pl/web/javascript/reference/global_objects/uint16array/index.html delete mode 100644 files/pl/web/javascript/reference/operators/instanceof/index.html delete mode 100644 files/pl/web/javascript/reference/operators/this/index.html delete mode 100644 files/pl/web/javascript/reference/statements/throw/index.html delete mode 100644 files/pl/web/javascript/typed_arrays/index.html (limited to 'files/pl/web/javascript') diff --git a/files/pl/web/javascript/data_structures/index.html b/files/pl/web/javascript/data_structures/index.html deleted file mode 100644 index 4a86825a9e..0000000000 --- a/files/pl/web/javascript/data_structures/index.html +++ /dev/null @@ -1,444 +0,0 @@ ---- -title: Typy oraz struktury danych w JavaScript -slug: Web/JavaScript/Data_structures -tags: - - JavaScript - - Początkujący - - Typy danych -translation_of: Web/JavaScript/Data_structures -original_slug: Web/JavaScript/typy_oraz_struktury_danych ---- -
{{jsSidebar("More")}}
- -
Wszystkie języki programowania posiadają wbudowane struktury danych, mogą one jednak różnic się między poszczególnymi językami. Poniższy artykuł jest próbą stworzenia listy wbudowanych typów oraz struktur danych w JavaScript oraz ich właściwości. Mogą być one użyte do tworzenia innych struktur danych. Tam gdzie jest to możliwe dokonano porównania z innymi językami programowania.
- -

Dynamiczne typowanie

- -

JavaScript jest językiem typowanym dynamicznie. Zmienne w Javascript nie są bezpośrednio powiązane z konkretnym typem wartości i możemy im przypisywać wartości dowolnego typu:

- -
let foo = 42;    // foo jest teraz liczbą (number)
-foo     = 'bar'; // foo jest teraz ciągiem znaków (string)
-foo     = true;  // foo jest teraz type logicznym (boolean)
-
- -

Data and Structure types

- -

Najnowsza wersja standardu ECMAScript definiuje dziewięć typów danych:

- - - -

Keep in mind the only valuable purpose of typeof operator usage is checking the Data Type. If we wish to check any Structural Type derived from Object it is pointless to use typeof for that, as we will always receive "object". The indeed proper way to check what sort of Object we are using an instanceof keyword. But even in that case there might be misconceptions.

- -

Wartości prymitywne

- -

All types except objects define immutable values (that is, values which can't be changed). For example (and unlike in C), Strings are immutable. We refer to values of these types as "primitive values".

- -

Boolean type

- -

Boolean represents a logical entity and can have two values: true and false. See Boolean and {{jsxref("Boolean")}} for more details.

- -

Null type

- -

The Null type has exactly one value: null. See {{jsxref("null")}} and Null for more details.

- -

Undefined type

- -

A variable that has not been assigned a value has the value undefined. See {{jsxref("undefined")}} and Undefined for more details.

- -

Number type

- -

ECMAScript has two built-in numeric types: Number and BigInt (see below).

- -

The Number type is a double-precision 64-bit binary format IEEE 754 value (numbers between -(253 − 1) and 253 − 1). In addition to representing floating-point numbers, the number type has three symbolic values: +Infinity, -Infinity, and {{jsxref("NaN")}} ("Not a Number").

- -

To check for the largest available value or smallest available value within {{jsxref("Infinity", "±Infinity")}}, you can use the constants {{jsxref("Number.MAX_VALUE")}} or {{jsxref("Number.MIN_VALUE")}}.

- -

Starting with ECMAScript 2015, you are also able to check if a number is in the double-precision floating-point number range using {{jsxref("Number.isSafeInteger()")}} as well as {{jsxref("Number.MAX_SAFE_INTEGER")}} and {{jsxref("Number.MIN_SAFE_INTEGER")}}. Beyond this range, integers in JavaScript are not safe anymore and will be a double-precision floating point approximation of the value.

- -

The number type has only one integer with two representations: 0 is represented as both -0 and +0. (0 is an alias for +0.) 

- -

In the praxis, this has almost no impact. For example, +0 === -0 is true. However, you are able to notice this when you divide by zero:

- -
> 42 / +0
-Infinity
-> 42 / -0
--Infinity
-
- -

Although a number often represents only its value, JavaScript provides {{jsxref("Operators/Bitwise_Operators", "binary (bitwise) operators")}}.

- -

These bitwise operators can be used to represent several Boolean values within a single number using bit masking. However, this is usually considered a bad practice, since JavaScript offers other means to represent a set of Booleans (like an array of Booleans, or an object with Boolean values assigned to named properties). Bit masking also tends to make the code more difficult to read, understand, and maintain.

- -

It may be necessary to use such techniques in very constrained environments, like when trying to cope with the limitations of local storage, or in extreme cases (such as when each bit over the network counts). This technique should only be considered when it is the last measure that can be taken to optimize size.

- -

BigInt type

- -

The {{jsxref("BigInt")}} type is a numeric primitive in JavaScript that can represent integers with arbitrary precision. With BigInts, you can safely store and operate on large integers even beyond the safe integer limit for Numbers.

- -

A BigInt is created by appending n to the end of an integer or by calling the constructor.

- -

You can obtain the safest value that can be incremented with Numbers by using the constant {{jsxref("Number.MAX_SAFE_INTEGER")}}. With the introduction of BigInts, you can operate with numbers beyond the {{jsxref("Number.MAX_SAFE_INTEGER")}}.

- -

This example demonstrates, where incrementing the {{jsxref("Number.MAX_SAFE_INTEGER")}} returns the expected result:

- -
> const x = 2n ** 53n;
-9007199254740992n
-> const y = x + 1n;
-9007199254740993n
-
- -

You can use the operators +, *, -, **, and % with BigInts—just like with Numbers. A BigInt is not strictly equal to a Number, but it is loosely so.

- -

A BigInt behaves like a Number in cases where it is converted to Boolean: if, ||, &&, Boolean, !.

- -

BigInts cannot be operated on interchangeably with Numbers. Instead a {{jsxref("TypeError")}} will be thrown.

- -

String type

- -

JavaScript's {{jsxref("String")}} type is used to represent textual data. It is a set of "elements" of 16-bit unsigned integer values. Each element in the String occupies a position in the String. The first element is at index 0, the next at index 1, and so on. The length of a String is the number of elements in it.

- -

Unlike some programming languages (such as C), JavaScript strings are immutable. This means that once a string is created, it is not possible to modify it.

- -

However, it is still possible to create another string based on an operation on the original string. For example:

- - - -

Beware of "stringly-typing" your code!

- -

It can be tempting to use strings to represent complex data. Doing this comes with short-term benefits:

- - - -

With conventions, it is possible to represent any data structure in a string. This does not make it a good idea. For instance, with a separator, one could emulate a list (while a JavaScript array would be more suitable). Unfortunately, when the separator is used in one of the "list" elements, then, the list is broken. An escape character can be chosen, etc. All of this requires conventions and creates an unnecessary maintenance burden.

- -

Use strings for textual data. When representing complex data, parse strings and use the appropriate abstraction.

- -

Symbol type

- -

Symbols are new to JavaScript in ECMAScript 2015. A Symbol is a unique and immutable primitive value and may be used as the key of an Object property (see below). In some programming languages, Symbols are called "atoms".

- -

For more details see Symbol and the {{jsxref("Symbol")}} object wrapper in JavaScript.

- -

Obiekty

- -

In computer science, an object is a value in memory which is possibly referenced by an identifier.

- -

Properties

- -

In JavaScript, objects can be seen as a collection of properties. With the object literal syntax, a limited set of properties are initialized; then properties can be added and removed. Property values can be values of any type, including other objects, which enables building complex data structures. Properties are identified using key values. A key value is either a String or a Symbol value.

- -

There are two types of object properties which have certain attributes: The data property and the accessor property.

- -

Data property

- -

Associates a key with a value, and has the following attributes:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Attributes of a data property
AttributeTypeDescriptionDefault value
[[Value]]Any JavaScript typeThe value retrieved by a get access of the property.undefined
[[Writable]]BooleanIf false, the property's [[Value]] cannot be changed.false
[[Enumerable]]Boolean -

If true, the property will be enumerated in for...in loops.
- See also Enumerability and ownership of properties.

-
false
[[Configurable]]BooleanIf false, the property cannot be deleted, cannot be changed to an accessor property, and attributes other than [[Value]] and [[Writable]] cannot be changed.false
- - - - - - - - - - - - - - - - - - - - - - - - - - - -
Obsolete attributes (as of ECMAScript 3, renamed in ECMAScript 5)
AttributeTypeDescription
Read-onlyBooleanReversed state of the ES5 [[Writable]] attribute.
DontEnumBooleanReversed state of the ES5 [[Enumerable]] attribute.
DontDeleteBooleanReversed state of the ES5 [[Configurable]] attribute.
- -

Accessor property

- -

Associates a key with one of two accessor functions (get and set) to retrieve or store a value, and has the following attributes:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Attributes of an accessor property
AttributeTypeDescriptionDefault value
[[Get]]Function object or undefinedThe function is called with an empty argument list and retrieves the property value whenever a get access to the value is performed.
- See also get.
undefined
[[Set]]Function object or undefinedThe function is called with an argument that contains the assigned value and is executed whenever a specified property is attempted to be changed.
- See also set.
undefined
[[Enumerable]]BooleanIf true, the property will be enumerated in for...in loops.false
[[Configurable]]BooleanIf false, the property can't be deleted and can't be changed to a data property.false
- -
-

Note: Attribute is usually used by JavaScript engine, so you can't directly access it (see more about {{jsxref("Object.defineProperty()")}}). That's why the attribute is put in double square brackets instead of single.

-
- -

"Normal" objects, and functions

- -

A JavaScript object is a mapping between keys and values. Keys are strings (or {{jsxref("Symbol")}}s), and values can be anything. This makes objects a natural fit for hashmaps.

- -

Functions are regular objects with the additional capability of being callable.

- -

Dates

- -

When representing dates, the best choice is to use the built-in Date utility in JavaScript.

- -

Indexed collections: Arrays and typed Arrays

- -

Arrays are regular objects for which there is a particular relationship between integer-key-ed properties and the length property.

- -

Additionally, arrays inherit from Array.prototype, which provides to them a handful of convenient methods to manipulate arrays. For example, indexOf (searching a value in the array) or push (adding an element to the array), and so on. This makes Arrays a perfect candidate to represent lists or sets.

- -

Typed Arrays are new to JavaScript with ECMAScript 2015, and present an array-like view of an underlying binary data buffer. The following table helps determine the equivalent C data types:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TypeValue RangeSize in bytesDescriptionWeb IDL typeEquivalent C type
{{jsxref("Int8Array")}}-128 to 12718-bit two's complement signed integerbyteint8_t
{{jsxref("Uint8Array")}}0 to 25518-bit unsigned integeroctetuint8_t
{{jsxref("Uint8ClampedArray")}}0 to 25518-bit unsigned integer (clamped)octetuint8_t
{{jsxref("Int16Array")}}-32768 to 32767216-bit two's complement signed integershortint16_t
{{jsxref("Uint16Array")}}0 to 65535216-bit unsigned integerunsigned shortuint16_t
{{jsxref("Int32Array")}}-2147483648 to 2147483647432-bit two's complement signed integerlongint32_t
{{jsxref("Uint32Array")}}0 to 4294967295432-bit unsigned integerunsigned longuint32_t
{{jsxref("Float32Array")}}1.2×10-38 to 3.4×1038432-bit IEEE floating point number (7 significant digits e.g., 1.1234567)unrestricted floatfloat
{{jsxref("Float64Array")}}5.0×10-324 to 1.8×10308864-bit IEEE floating point number (16 significant digits e.g., 1.123...15)unrestricted doubledouble
{{jsxref("BigInt64Array")}}-263 to 263-1864-bit two's complement signed integerbigintint64_t (signed long long)
{{jsxref("BigUint64Array")}}0 to 264-1864-bit unsigned integerbigintuint64_t (unsigned long long)
- -

Keyed collections: Maps, Sets, WeakMaps, WeakSets

- -

These data structures, introduced in ECMAScript Edition 6, take object references as keys. {{jsxref("Set")}} and {{jsxref("WeakSet")}} represent a set of objects, while {{jsxref("Map")}} and {{jsxref("WeakMap")}} associate a value to an object.

- -

The difference between Maps and WeakMaps is that in the former, object keys can be enumerated over. This allows garbage collection optimizations in the latter case.

- -

One could implement Maps and Sets in pure ECMAScript 5. However, since objects cannot be compared (in the sense of < "less than", for instance), look-up performance would necessarily be linear. Native implementations of them (including WeakMaps) can have look-up performance that is approximately logarithmic to constant time.

- -

Usually, to bind data to a DOM node, one could set properties directly on the object, or use data-* attributes. This has the downside that the data is available to any script running in the same context. Maps and WeakMaps make it easy to privately bind data to an object.

- -

Structured data: JSON

- -

JSON (JavaScript Object Notation) is a lightweight data-interchange format, derived from JavaScript, but used by many programming languages. JSON builds universal data structures.

- -

See JSON and {{jsxref("JSON")}} for more details.

- -

More objects in the standard library

- -

JavaScript has a standard library of built-in objects.

- -

Please have a look at the reference to find out about more objects.

- -

Określanie typu za pomocą operatora typeof

- -

Operator typeof może być pomocny przy określeniu typu twojej zmiennej.

- -

Więcej szczegółów znajdziecie na stronie poświęconej operatorowi typeof.

- -

Specifications

- - - - - - - - - - - - -
Specification
{{SpecName('ESDraft', '#sec-ecmascript-data-types-and-values', 'ECMAScript Data Types and Values')}}
- -

See also

- - diff --git a/files/pl/web/javascript/reference/deprecated_and_obsolete_features/index.html b/files/pl/web/javascript/reference/deprecated_and_obsolete_features/index.html deleted file mode 100644 index e937d7c66d..0000000000 --- a/files/pl/web/javascript/reference/deprecated_and_obsolete_features/index.html +++ /dev/null @@ -1,293 +0,0 @@ ---- -title: Przestarzałe własności i metody -slug: Web/JavaScript/Reference/Deprecated_and_obsolete_features -tags: - - Dokumentacja_JavaScript - - Dokumentacje - - JavaScript - - Strony_wymagające_dopracowania - - Wszystkie_kategorie -translation_of: Web/JavaScript/Reference/Deprecated_and_obsolete_features -original_slug: Web/JavaScript/Referencje/Przestarzałe_własności_i_metody ---- -
{{JsSidebar("More")}}
- -

This page lists features of JavaScript that are deprecated (that is, still available but planned for removal) and obsolete (that is, no longer usable).

- -

Deprecated features

- -

These deprecated features can still be used, but should be used with caution because they are expected to be removed entirely sometime in the future. You should work to remove their use from your code.

- -

RegExp properties

- -

The following properties are deprecated. This does not affect their use in {{jsxref("String.replace", "replacement strings", "", 1)}}:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
PropertyDescription
{{jsxref("RegExp.n", "$1-$9")}} -

Parenthesized substring matches, if any.
- Warning: Using these properties can result in problems, since browser extensions can modify them. Avoid them!

-
{{jsxref("RegExp.input", "$_")}}See input.
{{jsxref("RegExp.multiline", "$*")}}See multiline.
{{jsxref("RegExp.lastMatch", "$&")}}See lastMatch.
{{jsxref("RegExp.lastParen", "$+")}}See lastParen.
{{jsxref("RegExp.leftContext", "$`")}}See leftContext.
{{jsxref("RegExp.rightContext", "$'")}}See rightContext.
{{jsxref("RegExp.input", "input")}}The string against which a regular expression is matched.
{{jsxref("RegExp.lastMatch", "lastMatch")}}The last matched characters.
{{jsxref("RegExp.lastParen", "lastParen")}}The last parenthesized substring match, if any.
{{jsxref("RegExp.leftContext", "leftContext")}}The substring preceding the most recent match.
{{jsxref("RegExp.rightContext", "rightContext")}}The substring following the most recent match.
- -

The following are now properties of RegExp instances, no longer of the RegExp object:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - -
PropertyDescription
{{jsxref("RegExp.global", "global")}}Whether or not to test the regular expression against all possible matches in a string, or only against the first.
{{jsxref("RegExp.ignoreCase", "ignoreCase")}}Whether or not to ignore case while attempting a match in a string.
{{jsxref("RegExp.lastIndex", "lastIndex")}}The index at which to start the next match.
{{jsxref("RegExp.multiline", "multiline")}}Whether or not to search in strings across multiple lines.
{{jsxref("RegExp.source", "source")}}The text of the pattern.
- -

RegExp methods

- - - -

Function properties

- - - -

Legacy generator

- - - -

Iterator

- - - -

Object methods

- - - -

Date methods

- - - -

Functions

- - - -

Proxy

- - - -

Escape sequences

- - - -

String methods

- - - -

Obsolete features

- -

These obsolete features have been entirely removed from JavaScript and can no longer be used as of the indicated version of JavaScript.

- -

Object

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
PropertyDescription
{{jsxref("Global_Objects/Object/count", "__count__")}}Returns the number of enumerable properties directly on a user-defined object.
{{jsxref("Global_Objects/Object/Parent", "__parent__")}}Points to an object's context.
{{jsxref("Global_Objects/Object/eval", "Object.prototype.eval()")}}Evaluates a string of JavaScript code in the context of the specified object.
{{jsxref("Object.observe()")}}Asynchronously observing the changes to an object.
{{jsxref("Object.unobserve()")}}Remove observers.
{{jsxref("Object.getNotifier()")}}Creates an object that allows to synthetically trigger a change.
- -

Function

- - - - - - - - - - - - -
PropertyDescription
{{jsxref("Global_Objects/Function/arity", "arity")}}Number of formal arguments.
- -

Array

- - - - - - - - - - - - - - - - -
PropertyDescription
{{jsxref("Array.observe()")}}Asynchronously observing changes to Arrays.
{{jsxref("Array.unobserve()")}}Remove observers.
- -

Number

- - - -

ParallelArray

- - - -

Statements

- - - -

E4X

- -

See E4X for more information.

- -

Sharp variables

- -

See Sharp variables in JavaScript for more information.

diff --git a/files/pl/web/javascript/reference/global_objects/escape/index.html b/files/pl/web/javascript/reference/global_objects/escape/index.html deleted file mode 100644 index 2fcf67431d..0000000000 --- a/files/pl/web/javascript/reference/global_objects/escape/index.html +++ /dev/null @@ -1,121 +0,0 @@ ---- -title: escape() -slug: Web/JavaScript/Reference/Global_Objects/escape -translation_of: Web/JavaScript/Reference/Global_Objects/escape -original_slug: Web/JavaScript/Referencje/Obiekty/escape ---- -
{{jsSidebar("Objects")}}
- -

The deprecated escape() function computes a new string in which certain characters have been replaced by a hexadecimal escape sequence. Use {{jsxref("encodeURI")}} or {{jsxref("encodeURIComponent")}} instead.

- -

Składnia

- -
escape(str)
- -

Parametry

- -
-
str
-
A string to be encoded.
-
- -

Description

- -

The escape function is a property of the global object. Special characters are encoded with the exception of: @*_+-./

- -

The hexadecimal form for characters, whose code unit value is 0xFF or less, is a two-digit escape sequence: %xx. For characters with a greater code unit, the four-digit format %uxxxx is used.

- -

Przykłady

- -
escape("abc123");     // "abc123"
-escape("äöü");        // "%E4%F6%FC"
-escape("ć");          // "%u0107"
-
-// znaki specjalne
-escape("@*_+-./");    // "@*_+-./"
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition.
{{SpecName('ES5.1', '#sec-B.2.1', 'escape')}}{{Spec2('ES5.1')}}Defined in the (informative) Compatibility Annex B
{{SpecName('ES6', '#sec-escape-string', 'escape')}}{{Spec2('ES6')}}Defined in the (normative) Annex B for Additional ECMAScript Features for Web Browsers
- -

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/pl/web/javascript/reference/global_objects/generator/index.html b/files/pl/web/javascript/reference/global_objects/generator/index.html deleted file mode 100644 index a84467e7ca..0000000000 --- a/files/pl/web/javascript/reference/global_objects/generator/index.html +++ /dev/null @@ -1,179 +0,0 @@ ---- -title: Generator -slug: Web/JavaScript/Reference/Global_Objects/Generator -translation_of: Web/JavaScript/Reference/Global_Objects/Generator -original_slug: Web/JavaScript/Referencje/Obiekty/Generator ---- -
{{JSRef}}
- -

Obiekt Generator jest zwracany przez {{jsxref("Polecenia/function*", "generator function", "", 1)}} i odpowiada obu: iterable protocol i iterator protocol.

- -

Syntax

- -
function* gen() {
-  yield 1;
-  yield 2;
-  yield 3;
-}
-
-var g = gen(); // "Generator { }"
- -

Methods

- -
-
{{jsxref("Generator.prototype.next()")}}
-
Returns a value yielded by the {{jsxref("Operators/yield", "yield")}} expression.
-
{{jsxref("Generator.prototype.return()")}}
-
Returns the given value and finishes the generator.
-
{{jsxref("Generator.prototype.throw()")}}
-
Throws an error to a generator.
-
- -

Example

- -

An infinite iterator

- -
function* idMaker() {
-    var index = 0;
-    while(true)
-        yield index++;
-}
-
-var gen = idMaker(); // "Generator { }"
-
-console.log(gen.next().value); // 0
-console.log(gen.next().value); // 1
-console.log(gen.next().value); // 2
-// ...
- -

Legacy generator objects

- -

Firefox (SpiderMonkey) also implements an earlier version of generators in JavaScript 1.7, where the star (*) in the function declaration was not necessary (you just use the yield keyword in the function body). However, legacy generators are deprecated. Do not use them; they are going to be removed ({{bug(1083482)}}).

- -

Legacy generator methods

- -
-
Generator.prototype.next() {{non-standard_inline}}
-
Returns a value yielded by the {{jsxref("Operatory/yield", "yield")}} expression. This corresponds to next() in the ES2015 generator object.
-
Generator.prototype.close() {{non-standard_inline}}
-
Closes the generator, so that when calling next() an {{jsxref("StopIteration")}} error will be thrown. This corresponds to the return() method in the ES2015 generator object.
-
Generator.prototype.send() {{non-standard_inline}}
-
Used to send a value to a generator. The value is returned from the {{jsxref("Operatory/yield", "yield")}} expression, and returns a value yielded by the next {{jsxref("Operatory/yield", "yield")}} expression. send(x) corresponds to next(x) in the ES2015 generator object.
-
Generator.prototype.throw() {{non-standard_inline}}
-
Throws an error to a generator. This corresponds to the throw() method in the ES2015 generator object.
-
- -

Legacy generator example

- -
function fibonacci() {
-  var a = yield 1;
-  yield a * 2;
-}
-
-var it = fibonacci();
-console.log(it);          // "Generator {  }"
-console.log(it.next());   // 1
-console.log(it.send(10)); // 20
-console.log(it.close());  // undefined
-console.log(it.next());   // throws StopIteration (as the generator is now closed)
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES2015', '#sec-generator-objects', 'Generator objects')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-generator-objects', 'Generator objects')}}{{Spec2('ESDraft')}} 
- -

Browser compatibility

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome(39.0)}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatChrome(39.0)}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatChrome(39.0)}}
-
- -

See also

- -

Legacy generators

- - - -

ES2015 generators

- - diff --git a/files/pl/web/javascript/reference/global_objects/string/blink/index.html b/files/pl/web/javascript/reference/global_objects/string/blink/index.html deleted file mode 100644 index 7430744309..0000000000 --- a/files/pl/web/javascript/reference/global_objects/string/blink/index.html +++ /dev/null @@ -1,51 +0,0 @@ ---- -title: String.prototype.blink() -slug: Web/JavaScript/Reference/Global_Objects/String/blink -tags: - - Deprecated - - JavaScript - - Method - - Prototype - - String -translation_of: Web/JavaScript/Reference/Global_Objects/String/blink -original_slug: Web/JavaScript/Referencje/Obiekty/String/blink ---- -
{{JSRef}} {{deprecated_header}}
- -

Podsumowanie

- -

Powoduje, iż łańcuch będzie migotał tak, jakby był on wewnątrz znacznika {{HTMLElement("blink")}}.

- -
-

Warning: Blinking text is frowned upon by several accessibility standards. The <blink> element itself is non-standard and deprecated!

-
- -

Składnia

- -
str.blink()
- -

Opis

- -

The blink() method embeds a string in a <blink> tag: "<blink>str</blink>".

- -

Przykłady

- -

Przykład: Zastosowanie blink()

- -

Następujący przykład stosuje metodę string do zmiany formatowania łańcucha znaków:

- -
var worldString="Witaj, Świecie";
-
-console.log(worldString.blink());   // <blink>Witaj, Świecie</blink>
-console.log(worldString.bold());    // <bold>Witaj, Świecie</bold>
-console.log(worldString.italics()); // <i>Witaj, Świecie</i>
-console.log(worldString.strike());  // <s>Witaj, Świecie</s>
-
- -

Zobacz także

- - diff --git a/files/pl/web/javascript/reference/global_objects/string/fromcodepoint/index.html b/files/pl/web/javascript/reference/global_objects/string/fromcodepoint/index.html deleted file mode 100644 index 0a3bacc072..0000000000 --- a/files/pl/web/javascript/reference/global_objects/string/fromcodepoint/index.html +++ /dev/null @@ -1,148 +0,0 @@ ---- -title: String.fromCodePoint() -slug: Web/JavaScript/Reference/Global_Objects/String/fromCodePoint -translation_of: Web/JavaScript/Reference/Global_Objects/String/fromCodePoint -original_slug: Web/JavaScript/Referencje/Obiekty/String/fromCodePoint ---- -
{{JSRef}}
- -

The static String.fromCodePoint() method returns a string created by using the specified sequence of code points.

- -
{{EmbedInteractiveExample("pages/js/string-fromcodepoint.html","shorter")}}
- - - -

Syntax

- -
String.fromCodePoint(num1[, ...[, numN]])
- -

Parameters

- -
-
num1, ..., numN
-
A sequence of code points.
-
- -

Return value

- -

A string created by using the specified sequence of code points.

- -

Exceptions

- - - -

Description

- -

This method returns a string (and not a {{jsxref("String")}} object).

- -

Because fromCodePoint() is a static method of {{jsxref("String")}}, you must call it as String.fromCodePoint(), rather than as a method of a {{jsxref("String")}} object you created.

- -

Polyfill

- -

The String.fromCodePoint() method has been added to ECMAScript 2015 and may not be supported in all web browsers or environments yet.

- -

Use the code below for a polyfill:

- -
if (!String.fromCodePoint) (function(stringFromCharCode) {
-    var fromCodePoint = function(_) {
-      var codeUnits = [], codeLen = 0, result = "";
-      for (var index=0, len = arguments.length; index !== len; ++index) {
-        var codePoint = +arguments[index];
-        // correctly handles all cases including `NaN`, `-Infinity`, `+Infinity`
-        // The surrounding `!(...)` is required to correctly handle `NaN` cases
-        // The (codePoint>>>0) === codePoint clause handles decimals and negatives
-        if (!(codePoint < 0x10FFFF && (codePoint>>>0) === codePoint))
-          throw RangeError("Invalid code point: " + codePoint);
-        if (codePoint <= 0xFFFF) { // BMP code point
-          codeLen = codeUnits.push(codePoint);
-        } else { // Astral code point; split in surrogate halves
-          // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
-          codePoint -= 0x10000;
-          codeLen = codeUnits.push(
-            (codePoint >> 10) + 0xD800,  // highSurrogate
-            (codePoint % 0x400) + 0xDC00 // lowSurrogate
-          );
-        }
-        if (codeLen >= 0x3fff) {
-          result += stringFromCharCode.apply(null, codeUnits);
-          codeUnits.length = 0;
-        }
-      }
-      return result + stringFromCharCode.apply(null, codeUnits);
-    };
-    try { // IE 8 only supports `Object.defineProperty` on DOM elements
-      Object.defineProperty(String, "fromCodePoint", {
-        "value": fromCodePoint, "configurable": true, "writable": true
-      });
-    } catch(e) {
-      String.fromCodePoint = fromCodePoint;
-    }
-}(String.fromCharCode));
-
- -

Examples

- -

Using fromCodePoint()

- -

Valid input:

- -
String.fromCodePoint(42);       // "*"
-String.fromCodePoint(65, 90);   // "AZ"
-String.fromCodePoint(0x404);    // "\u0404" == "Є"
-String.fromCodePoint(0x2F804);  // "\uD87E\uDC04"
-String.fromCodePoint(194564);   // "\uD87E\uDC04"
-String.fromCodePoint(0x1D306, 0x61, 0x1D307); // "\uD834\uDF06a\uD834\uDF07"
-
- -

Invalid input:

- -
String.fromCodePoint('_');      // RangeError
-String.fromCodePoint(Infinity); // RangeError
-String.fromCodePoint(-1);       // RangeError
-String.fromCodePoint(3.14);     // RangeError
-String.fromCodePoint(3e-2);     // RangeError
-String.fromCodePoint(NaN);      // RangeError
-
- -

Compared to fromCharCode()

- -

{{jsxref("String.fromCharCode()")}} cannot return supplementary characters (i.e. code points 0x0100000x10FFFF) by specifying their code point. Instead, it requires the UTF-16 surrogate pair in order to return a supplementary character:

- -
String.fromCharCode(0xD83C, 0xDF03); // Code Point U+1F303 "Night with
-String.fromCharCode(55356, 57091);   // Stars" == "\uD83C\uDF03"
-
- -

String.fromCodePoint(), on the other hand, can return 4-byte supplementary characters, as well as the more common 2-byte BMP characters, by specifying their code point (which is equivalent to the UTF-32 code unit):

- -
String.fromCodePoint(0x1F303); // or 127747 in decimal
-
- -

Specifications

- - - - - - - - - - - - -
Specification
{{SpecName('ESDraft', '#sec-string.fromcodepoint', 'String.fromCodePoint')}}
- -

Browser compatibility

- -

{{Compat("javascript.builtins.String.fromCodePoint")}}

- -

See also

- - diff --git a/files/pl/web/javascript/reference/global_objects/string/repeat/index.html b/files/pl/web/javascript/reference/global_objects/string/repeat/index.html deleted file mode 100644 index a6542a4bb7..0000000000 --- a/files/pl/web/javascript/reference/global_objects/string/repeat/index.html +++ /dev/null @@ -1,167 +0,0 @@ ---- -title: String.prototype.repeat() -slug: Web/JavaScript/Reference/Global_Objects/String/repeat -translation_of: Web/JavaScript/Reference/Global_Objects/String/repeat -original_slug: Web/JavaScript/Referencje/Obiekty/String/repeat ---- -
{{JSRef}}
- -

The repeat() method constructs and returns a new string which contains the specified number of copies of the string on which it was called, concatenated together.

- -

Składnia

- -
str.repeat(count)
- -

Parametry

- -
-
count
-
An integer between 0 and +∞: [0, +∞), indicating the number of times to repeat the string in the newly-created string that is to be returned.
-
- -

Zwracana wartość

- -

A new string containing the specified number of copies of the given string.

- -

Exceptions

- - - -

Przykłady

- -
'abc'.repeat(-1);   // RangeError
-'abc'.repeat(0);    // ''
-'abc'.repeat(1);    // 'abc'
-'abc'.repeat(2);    // 'abcabc'
-'abc'.repeat(3.5);  // 'abcabcabc' (count will be converted to integer)
-'abc'.repeat(1/0);  // RangeError
-
-({ toString: () => 'abc', repeat: String.prototype.repeat }).repeat(2);
-// 'abcabc' (repeat() is a generic method)
-
- -

Polyfill

- -

This method has been added to the ECMAScript 6 specification and may not be available in all JavaScript implementations yet. However, you can polyfill String.prototype.repeat() with the following snippet:

- -
if (!String.prototype.repeat) {
-  String.prototype.repeat = function(count) {
-    'use strict';
-    if (this == null) {
-      throw new TypeError('can\'t convert ' + this + ' to object');
-    }
-    var str = '' + this;
-    count = +count;
-    if (count != count) {
-      count = 0;
-    }
-    if (count < 0) {
-      throw new RangeError('repeat count must be non-negative');
-    }
-    if (count == Infinity) {
-      throw new RangeError('repeat count must be less than infinity');
-    }
-    count = Math.floor(count);
-    if (str.length == 0 || count == 0) {
-      return '';
-    }
-    // Ensuring count is a 31-bit integer allows us to heavily optimize the
-    // main part. But anyway, most current (August 2014) browsers can't handle
-    // strings 1 << 28 chars or longer, so:
-    if (str.length * count >= 1 << 28) {
-      throw new RangeError('repeat count must not overflow maximum string size');
-    }
-    var rpt = '';
-    for (;;) {
-      if ((count & 1) == 1) {
-        rpt += str;
-      }
-      count >>>= 1;
-      if (count == 0) {
-        break;
-      }
-      str += str;
-    }
-    // Could we try:
-    // return Array(count + 1).join(this);
-    return rpt;
-  }
-}
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES6', '#sec-string.prototype.repeat', 'String.prototype.repeat')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-string.prototype.repeat', 'String.prototype.repeat')}}{{Spec2('ESDraft')}} 
- -

Browser compatibility

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("41")}} {{CompatGeckoDesktop("24")}}{{CompatNo}}{{CompatNo}}{{CompatSafari("9")}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatChrome("36")}}{{CompatGeckoMobile("24")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
diff --git a/files/pl/web/javascript/reference/global_objects/uint16array/index.html b/files/pl/web/javascript/reference/global_objects/uint16array/index.html deleted file mode 100644 index 759ad9d56e..0000000000 --- a/files/pl/web/javascript/reference/global_objects/uint16array/index.html +++ /dev/null @@ -1,225 +0,0 @@ ---- -title: Uint16Array -slug: Web/JavaScript/Reference/Global_Objects/Uint16Array -translation_of: Web/JavaScript/Reference/Global_Objects/Uint16Array -original_slug: Web/JavaScript/Referencje/Obiekty/Uint16Array ---- -
{{JSRef("Global_Objects", "TypedArray", "Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array")}}
- -

Summary

- -

The Uint16Array typed array represents an array of 16-bit unsigned integers in the platform byte order. If control over byte order is needed, use {{jsxref("DataView")}} instead. The contents are initialized to 0. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation).

- -

Syntax

- -
Uint16Array(length);
-Uint16Array(typedArray);
-Uint16Array(object);
-Uint16Array(buffer [, byteOffset [, length]]);
- -

For more information about the constructor syntax and the parameters, see TypedArray.

- -

Properties

- -
-
{{jsxref("TypedArray.BYTES_PER_ELEMENT", "Uint16Array.BYTES_PER_ELEMENT")}}
-
Returns a number value of the element size. 2 in the case of an Uint16Array.
-
Uint16Array.length
-
Length property whose value is 3.
-
{{jsxref("TypedArray.name", "Uint16Array.name")}}
-
Returns the string value of the constructor name. In the case of the Uint16Array type: "Uint16Array".
-
{{jsxref("TypedArray.prototype", "Uint16Array.prototype")}}
-
Prototype for the TypedArray objects.
-
- -

Methods

- -
-
{{jsxref("TypedArray.from", "Uint16Array.from()")}}
-
Creates a new Uint16Array from an array-like or iterable object. See also {{jsxref("Array.from()")}}.
-
{{jsxref("TypedArray.of", "Uint16Array.of()")}}
-
Creates a new Uint16Array with a variable number of arguments. See also {{jsxref("Array.of()")}}.
-
- -

Uint16Array prototype

- -

All Uint16Array objects inherit from {{jsxref("TypedArray.prototype", "%TypedArray%.prototype")}}.

- -

Properties

- -
-
Uint16Array.prototype.constructor
-
Returns the function that created an instance's prototype. This is the Uint16Array constructor by default.
-
{{jsxref("TypedArray.prototype.buffer", "Uint16Array.prototype.buffer")}} {{readonlyInline}}
-
Returns the {{jsxref("ArrayBuffer")}} referenced by the Uint16Array Fixed at construction time and thus read only.
-
{{jsxref("TypedArray.prototype.byteLength", "Uint16Array.prototype.byteLength")}} {{readonlyInline}}
-
Returns the length (in bytes) of the Uint16Array from the start of its {{jsxref("ArrayBuffer")}}. Fixed at construction time and thus read only.
-
{{jsxref("TypedArray.prototype.byteOffset", "Uint16Array.prototype.byteOffset")}} {{readonlyInline}}
-
Returns the offset (in bytes) of the Uint16Array from the start of its {{jsxref("ArrayBuffer")}}. Fixed at construction time and thus read only.
-
{{jsxref("TypedArray.prototype.length", "Uint16Array.prototype.length")}} {{readonlyInline}}
-
Returns the number of elements hold in the Uint16Array. Fixed at construction time and thus read only.
-
- -

Methods

- -
-
{{jsxref("TypedArray.copyWithin", "Uint16Array.prototype.copyWithin()")}}
-
Copies a sequence of array elements within the array. See also {{jsxref("Array.prototype.copyWithin()")}}.
-
{{jsxref("TypedArray.entries", "Uint16Array.prototype.entries()")}}
-
Returns a new Array Iterator object that contains the key/value pairs for each index in the array. See also {{jsxref("Array.prototype.entries()")}}.
-
{{jsxref("TypedArray.every", "Uint16Array.prototype.every()")}}
-
Tests whether all elements in the array pass the test provided by a function. See also {{jsxref("Array.prototype.every()")}}.
-
{{jsxref("TypedArray.fill", "Uint16Array.prototype.fill()")}}
-
Fills all the elements of an array from a start index to an end index with a static value. See also {{jsxref("Array.prototype.fill()")}}.
-
{{jsxref("TypedArray.filter", "Uint16Array.prototype.filter()")}}
-
Creates a new array with all of the elements of this array for which the provided filtering function returns true. See also {{jsxref("Array.prototype.filter()")}}.
-
{{jsxref("TypedArray.find", "Uint16Array.prototype.find()")}}
-
Returns the found value in the array, if an element in the array satisfies the provided testing function or undefined if not found. See also {{jsxref("Array.prototype.find()")}}.
-
{{jsxref("TypedArray.findIndex", "Uint16Array.prototype.findIndex()")}}
-
Returns the found index in the array, if an element in the array satisfies the provided testing function or -1 if not found. See also {{jsxref("Array.prototype.findIndex()")}}.
-
{{jsxref("TypedArray.forEach", "Uint16Array.prototype.forEach()")}}
-
Calls a function for each element in the array. See also {{jsxref("Array.prototype.forEach()")}}.
-
{{jsxref("TypedArray.includes", "Uint16Array.prototype.includes()")}} {{experimental_inline}}
-
Determines whether a typed array includes a certain element, returning true or false as appropriate. See also {{jsxref("Array.prototype.includes()")}}.
-
{{jsxref("TypedArray.indexOf", "Uint16Array.prototype.indexOf()")}}
-
Returns the first (least) index of an element within the array equal to the specified value, or -1 if none is found. See also {{jsxref("Array.prototype.indexOf()")}}.
-
{{jsxref("TypedArray.join", "Uint16Array.prototype.join()")}}
-
Joins all elements of an array into a string. See also {{jsxref("Array.prototype.join()")}}.
-
{{jsxref("TypedArray.keys", "Uint16Array.prototype.keys()")}}
-
Returns a new Array Iterator that contains the keys for each index in the array. See also {{jsxref("Array.prototype.keys()")}}.
-
{{jsxref("TypedArray.lastIndexOf", "Uint16Array.prototype.lastIndexOf()")}}
-
Returns the last (greatest) index of an element within the array equal to the specified value, or -1 if none is found. See also {{jsxref("Array.prototype.lastIndexOf()")}}.
-
{{jsxref("TypedArray.map", "Uint16Array.prototype.map()")}}
-
Creates a new array with the results of calling a provided function on every element in this array. See also {{jsxref("Array.prototype.map()")}}.
-
{{jsxref("TypedArray.move", "Uint16Array.prototype.move()")}} {{non-standard_inline}} {{unimplemented_inline}}
-
Former non-standard version of {{jsxref("TypedArray.copyWithin", "Uint16Array.prototype.copyWithin()")}}.
-
{{jsxref("TypedArray.reduce", "Uint16Array.prototype.reduce()")}}
-
Apply a function against an accumulator and each value of the array (from left-to-right) as to reduce it to a single value. See also {{jsxref("Array.prototype.reduce()")}}.
-
{{jsxref("TypedArray.reduceRight", "Uint16Array.prototype.reduceRight()")}}
-
Apply a function against an accumulator and each value of the array (from right-to-left) as to reduce it to a single value. See also {{jsxref("Array.prototype.reduceRight()")}}.
-
{{jsxref("TypedArray.reverse", "Uint16Array.prototype.reverse()")}}
-
Reverses the order of the elements of an array — the first becomes the last, and the last becomes the first. See also {{jsxref("Array.prototype.reverse()")}}.
-
{{jsxref("TypedArray.set", "Uint16Array.prototype.set()")}}
-
Stores multiple values in the typed array, reading input values from a specified array.
-
{{jsxref("TypedArray.slice", "Uint16Array.prototype.slice()")}}
-
Extracts a section of an array and returns a new array. See also {{jsxref("Array.prototype.slice()")}}.
-
{{jsxref("TypedArray.some", "Uint16Array.prototype.some()")}}
-
Returns true if at least one element in this array satisfies the provided testing function. See also {{jsxref("Array.prototype.some()")}}.
-
{{jsxref("TypedArray.sort", "Uint16Array.prototype.sort()")}}
-
Sorts the elements of an array in place and returns the array. See also {{jsxref("Array.prototype.sort()")}}.
-
{{jsxref("TypedArray.subarray", "Uint16Array.prototype.subarray()")}}
-
Returns a new Uint16Array from the given start and end element index.
-
{{jsxref("TypedArray.values", "Uint16Array.prototype.values()")}}
-
Returns a new Array Iterator object that contains the values for each index in the array. See also {{jsxref("Array.prototype.values()")}}.
-
{{jsxref("TypedArray.toLocaleString", "Uint16Array.prototype.toLocaleString()")}}
-
Returns a localized string representing the array and its elements. See also {{jsxref("Array.prototype.toLocaleString()")}}.
-
{{jsxref("TypedArray.toString", "Uint16Array.prototype.toString()")}}
-
Returns a string representing the array and its elements. See also {{jsxref("Array.prototype.toString()")}}.
-
{{jsxref("TypedArray.@@iterator", "Uint16Array.prototype[@@iterator]()")}}
-
Returns a new Array Iterator object that contains the values for each index in the array.
-
- -

Examples

- -
// From a length
-var uint16 = new Uint16Array(2);
-uint16[0] = 42;
-console.log(uint16[0]); // 42
-console.log(uint16.length); // 2
-console.log(uint16.BYTES_PER_ELEMENT); // 2
-
-// From an array
-var arr = new Uint16Array([21,31]);
-console.log(arr[1]); // 31
-
-// From another TypedArray
-var x = new Uint16Array([21, 31]);
-var y = new Uint16Array(x);
-console.log(y[0]); // 21
-
-// From an ArrayBuffer
-var buffer = new ArrayBuffer(8);
-var z = new Uint16Array(buffer, 0, 4);
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
Typed Array SpecificationObsoleteSuperseded by ECMAScript 6.
{{SpecName('ES6', '#table-45', 'TypedArray constructors')}}{{Spec2('ES6')}}Initial definition in an ECMA standard.
- -

Browser compatibility

- -

{{ CompatibilityTable() }}

- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support7.0{{ CompatGeckoDesktop("2") }}1011.65.1
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support4.0{{ CompatVersionUnknown() }}{{ CompatGeckoMobile("2") }}1011.64.2
-
- -

See also

- - diff --git a/files/pl/web/javascript/reference/operators/instanceof/index.html b/files/pl/web/javascript/reference/operators/instanceof/index.html deleted file mode 100644 index bd98d29e0f..0000000000 --- a/files/pl/web/javascript/reference/operators/instanceof/index.html +++ /dev/null @@ -1,169 +0,0 @@ ---- -title: Operator instanceof -slug: Web/JavaScript/Reference/Operators/instanceof -tags: - - Dokumentacja_JavaScript - - Dokumentacje - - JavaScript - - Strony_wymagające_dopracowania - - Wszystkie_kategorie -translation_of: Web/JavaScript/Reference/Operators/instanceof -original_slug: Web/JavaScript/Referencje/Operatory/Operator_instanceof ---- -
{{jsSidebar("Operators")}}
- -

Operator instanceof sprawdza czy właściwość konstruktora prototype pojawia się gdziekolwiek w łańcuchu prototypowym obiektu.

- -

{{EmbedInteractiveExample("pages/js/expressions-instanceof.html")}}

- - - -

Składnia

- -
object instanceof constructor
- -
-
-

Parametry

- object
-
Obiekt do testowania.
-
- -
-
constructor
-
Funkcja przeciwko której testujemy.
-
- -

Opis

- -

Operator instanceof sprawdza obecność constructor.prototype w łańcuchu prototypowym obiektu object

- -
// definiowanie konstruktorów
-function C() {}
-function D() {}
-
-var o = new C();
-
-// true, ponieważ: Object.getPrototypeOf(o) === C.prototype
-o instanceof C;
-
-// false, ponieważ D.prototype nie występuje w łańcuchu prototypowym o.
-o instanceof D;
-
-o instanceof Object; // true, ponieważ:
-C.prototype instanceof Object // true
-
-C.prototype = {};
-var o2 = new C();
-
-o2 instanceof C; // true
-
-// false, ponieważ C.prototype nie ma już w łańcuchu prototypowym o
-o instanceof C;
-
-D.prototype = new C(); // add C to [[Prototype]] linkage of D
-var o3 = new D();
-o3 instanceof D; // true
-o3 instanceof C; // true since C.prototype is now in o3's prototype chain
-
- -

Note that the value of an instanceof test can change based on changes to the prototype property of constructors, and it can also be changed by changing an object prototype using Object.setPrototypeOf. It is also possible using the non-standard __proto__ pseudo-property.

- -

instanceof and multiple context (e.g. frames or windows)

- -

Different scopes have different execution environments. This means that they have different built-ins (different global object, different constructors, etc.). This may result in unexpected results. For instance, [] instanceof window.frames[0].Array will return false, because Array.prototype !== window.frames[0].Array and arrays inherit from the former.

- -

This may not make sense at first but when you start dealing with multiple frames or windows in your script and pass objects from one context to another via functions, this will be a valid and strong issue. For instance, you can securely check if a given object is, in fact, an Array using Array.isArray(myObj)

- -

For example checking if a Nodes is a SVGElement in a different context you can use myNode instanceof myNode.ownerDocument.defaultView.SVGElement

- -
Note for Mozilla developers:
-In code using XPCOM instanceof has special effect: obj instanceof xpcomInterface (e.g. Components.interfaces.nsIFile) calls obj.QueryInterface(xpcomInterface) and returns true if QueryInterface succeeded. A side effect of such call is that you can use xpcomInterface's properties on obj after a successful instanceof test. Unlike standard JavaScript globals, the test obj instanceof xpcomInterface works as expected even if obj is from a different scope.
- -

Examples

- -

Demonstrating that String and Date are of type Object and exceptional cases

- -

The following code uses instanceof to demonstrate that String and Date objects are also of type Object (they are derived from Object).

- -

However, objects created with the object literal notation are an exception here: Although the prototype is undefined, instanceof Object returns true.

- -
var simpleStr = 'This is a simple string';
-var myString  = new String();
-var newStr    = new String('String created with constructor');
-var myDate    = new Date();
-var myObj     = {};
-
-simpleStr instanceof String; // returns false, checks the prototype chain, finds undefined
-myString  instanceof String; // returns true
-newStr    instanceof String; // returns true
-myString  instanceof Object; // returns true
-
-myObj instanceof Object;    // returns true, despite an undefined prototype
-({})  instanceof Object;    // returns true, same case as above
-
-myString instanceof Date;   // returns false
-
-myDate instanceof Date;     // returns true
-myDate instanceof Object;   // returns true
-myDate instanceof String;   // returns false
-
- -

Demonstrating that mycar is of type Car and type Object

- -

The following code creates an object type Car and an instance of that object type, mycar. The instanceof operator demonstrates that the mycar object is of type Car and of type Object.

- -
function Car(make, model, year) {
-  this.make = make;
-  this.model = model;
-  this.year = year;
-}
-var mycar = new Car('Honda', 'Accord', 1998);
-var a = mycar instanceof Car;    // returns true
-var b = mycar instanceof Object; // returns true
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-relational-operators', 'Relational Operators')}}{{Spec2('ESDraft')}} 
{{SpecName('ES6', '#sec-relational-operators', 'Relational Operators')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-11.8.6', 'The instanceof operator')}}{{Spec2('ES5.1')}} 
{{SpecName('ES3', '#sec-11.8.6', 'The instanceof operator')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.4.
- -

Browser compatibility

- - - -

{{Compat("javascript.operators.instanceof")}}

- -

See also

- - diff --git a/files/pl/web/javascript/reference/operators/this/index.html b/files/pl/web/javascript/reference/operators/this/index.html deleted file mode 100644 index 427d3f843e..0000000000 --- a/files/pl/web/javascript/reference/operators/this/index.html +++ /dev/null @@ -1,347 +0,0 @@ ---- -title: this -slug: Web/JavaScript/Reference/Operators/this -translation_of: Web/JavaScript/Reference/Operators/this -original_slug: Web/JavaScript/Referencje/Operatory/this ---- -
-
{{jsSidebar("Operators")}}
-
- -

Summary

- -

W JavaScript słówko kluczowe this zachowuje się nieco inaczej w porównaniu do innych języków programowania. Istnieje również kilka różnic między trybem strict mode oraz non-strict mode.

- -

W większości przypadków wartość this jest ustalana na podstawie tego, jak wywołana została dana funkcja. Wartość ta nie może być przypisana podczas wykonywania się funkcji i może być inna za każdym wywołaniem. ES5 wprowadziło metodę bind dzięki której możemy przypisać wartość this w funkcji, niezależnie od tego jak została ona wywołana.

- -

Syntax

- -
this
- -

Global context

- -

In the global execution context (outside of any function), this refers to the global object, whether in strict mode or not.

- -
console.log(this.document === document); // true
-
-// In web browsers, the window object is also the global object:
-console.log(this === window); // true
-
-this.a = 37;
-console.log(window.a); // 37
-
- -

Function context

- -

Inside a function, the value of this depends on how the function is called.

- -

Simple call

- -
function f1(){
-  return this;
-}
-
-f1() === window; // global object
-
- -

In this case, the value of this is not set by the call. Since the code is not in strict mode, the value of this must always be an object so it defaults to the global object.

- -
function f2(){
-  "use strict"; // see strict mode
-  return this;
-}
-
-f2() === undefined;
-
- -

In strict mode, the value of this remains at whatever it's set to when entering the execution context. If it's not defined, it remains undefined. It can also be set to any value, such as null or 42 or "I am not this".

- -
Note: In the second example, this should be undefined, because f2 was called without providing any base (e.g. window.f2()). This feature wasn't implemented in some browsers when they first started to support strict mode. As a result, they incorrectly returned the window object.
- -

As an object method

- -

When a function is called as a method of an object, its this is set to the object the method is called on.

- -

In the following example, when o.f() is invoked, inside the function this is bound to the o object.

- -
var o = {
-  prop: 37,
-  f: function() {
-    return this.prop;
-  }
-};
-
-console.log(o.f()); // logs 37
-
- -

Note that this behavior is not at all affected by how or where the function was defined. In the previous example, we defined the function inline as the f member during the definition of o. However, we could have just as easily defined the function first and later attached it to o.f. Doing so results in the same behavior:

- -
var o = {prop: 37};
-
-function independent() {
-  return this.prop;
-}
-
-o.f = independent;
-
-console.log(o.f()); // logs 37
-
- -

This demonstrates that it matters only that the function was invoked from the f member of o.

- -

Similarly, the this binding is only affected by the most immediate member reference. In the following example, when we invoke the function, we call it as a method g of the object o.b. This time during execution, this inside the function will refer to o.b. The fact that the object is itself a member of o has no consequence; the most immediate reference is all that matters.

- -
o.b = {g: independent, prop: 42};
-console.log(o.b.g()); // logs 42
-
- -

this on the object's prototype chain

- -

The same notion holds true for methods defined somewhere on the object's prototype chain. If the method is on an object's prototype chain, this refers to the object the method was called on, as if the method was on the object.

- -
var o = {f:function(){ return this.a + this.b; }};
-var p = Object.create(o);
-p.a = 1;
-p.b = 4;
-
-console.log(p.f()); // 5
-
- -

In this example, the object assigned to the variable p doesn't have its own f property, it inherits it from its prototype. But it doesn't matter that the lookup for f eventually finds a member with that name on o; the lookup began as a reference to p.f, so this inside the function takes the value of the object referred to as p. That is, since f is called as a method of p, its this refers to p. This is an interesting feature of JavaScript's prototype inheritance.

- -

this with a getter or setter

- -

Again, the same notion holds true when a function is invoked from a getter or a setter. A function used as getter or setter has its this bound to the object from which the property is being set or gotten.

- -
function modulus(){
-  return Math.sqrt(this.re * this.re + this.im * this.im);
-}
-
-var o = {
-  re: 1,
-  im: -1,
-  get phase(){
-    return Math.atan2(this.im, this.re);
-  }
-};
-
-Object.defineProperty(o, 'modulus', {
-    get: modulus, enumerable:true, configurable:true});
-
-console.log(o.phase, o.modulus); // logs -0.78 1.4142
-
- -

As a constructor

- -

When a function is used as a constructor (with the new keyword), its this is bound to new object being constructed.

- -

Note: while the default for a constructor is to return the object referenced by this, it can instead return some other object (if the return value isn't an object, then the this object is returned).

- -
/*
- * Constructors work like this:
- *
- * function MyConstructor(){
- *   // Actual function body code goes here.
- *   // Create properties on |this| as
- *   // desired by assigning to them.  E.g.,
- *   this.fum = "nom";
- *   // et cetera...
- *
- *   // If the function has a return statement that
- *   // returns an object, that object will be the
- *   // result of the |new| expression.  Otherwise,
- *   // the result of the expression is the object
- *   // currently bound to |this|
- *   // (i.e., the common case most usually seen).
- * }
- */
-
-function C(){
-  this.a = 37;
-}
-
-var o = new C();
-console.log(o.a); // logs 37
-
-
-function C2(){
-  this.a = 37;
-  return {a:38};
-}
-
-o = new C2();
-console.log(o.a); // logs 38
-
- -

In the last example (C2), because an object was returned during construction, the new object that this was bound to simply gets discarded. (This essentially makes the statement "this.a = 37;" dead code. It's not exactly dead, because it gets executed, but it can be eliminated with no outside effects.)

- -

call and apply

- -

Where a function uses the this keyword in its body, its value can be bound to a particular object in the call using the call or apply methods that all functions inherit from Function.prototype.

- -
function add(c, d){
-  return this.a + this.b + c + d;
-}
-
-var o = {a:1, b:3};
-
-// The first parameter is the object to use as
-// 'this', subsequent parameters are passed as
-// arguments in the function call
-add.call(o, 5, 7); // 1 + 3 + 5 + 7 = 16
-
-// The first parameter is the object to use as
-// 'this', the second is an array whose
-// members are used as the arguments in the function call
-add.apply(o, [10, 20]); // 1 + 3 + 10 + 20 = 34
-
- -

Note that with call and apply, if the value passed as this is not an object, an attempt will be made to convert it to an object using the internal ToObject operation. So if the value passed is a primitive like 7 or 'foo', it will be converted to an Object using the related constructor, so the primitive number 7 is converted to an object as if by new Number(7) and the string 'foo' to an object as if by new String('foo'), e.g.

- -
function bar() {
-  console.log(Object.prototype.toString.call(this));
-}
-
-bar.call(7); // [object Number]
-
- -

The bind method

- -

ECMAScript 5 introduced Function.prototype.bind. Calling f.bind(someObject) creates a new function with the same body and scope as f, but where this occurs in the original function, in the new function it is permanently bound to the first argument of bind, regardless of how the function is being used.

- -
function f(){
-  return this.a;
-}
-
-var g = f.bind({a:"azerty"});
-console.log(g()); // azerty
-
-var o = {a:37, f:f, g:g};
-console.log(o.f(), o.g()); // 37, azerty
-
- -

As a DOM event handler

- -

When a function is used as an event handler, its this is set to the element the event fired from (some browsers do not follow this convention for listeners added dynamically with methods other than addEventListener).

- -
// When called as a listener, turns the related element blue
-function bluify(e){
-  // Always true
-  console.log(this === e.currentTarget);
-  // true when currentTarget and target are the same object
-  console.log(this === e.target);
-  this.style.backgroundColor = '#A5D9F3';
-}
-
-// Get a list of every element in the document
-var elements = document.getElementsByTagName('*');
-
-// Add bluify as a click listener so when the
-// element is clicked on, it turns blue
-for(var i=0 ; i<elements.length ; i++){
-  elements[i].addEventListener('click', bluify, false);
-}
- -

In an in–line event handler

- -

When code is called from an in–line handler, its this is set to the DOM element on which the listener is placed:

- -
<button onclick="alert(this.tagName.toLowerCase());">
-  Show this
-</button>
-
- -

The above alert shows button. Note however that only the outer code has its this set this way:

- -
<button onclick="alert((function(){return this}()));">
-  Show inner this
-</button>
-
- -

In this case, the inner function's this isn't set so it returns the global/window object (i.e. the default object in non–strict mode where this isn't set by the call).

- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
ECMAScript 1st Edition.StandardInitial definition. Implemented in JavaScript 1.0
{{SpecName('ES5.1', '#sec-11.1.1', 'The this keyword')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-this-keyword', 'The this keyword')}}{{Spec2('ES6')}}
- -

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/pl/web/javascript/reference/statements/throw/index.html b/files/pl/web/javascript/reference/statements/throw/index.html deleted file mode 100644 index d47ab9803b..0000000000 --- a/files/pl/web/javascript/reference/statements/throw/index.html +++ /dev/null @@ -1,198 +0,0 @@ ---- -title: throw -slug: Web/JavaScript/Reference/Statements/throw -tags: - - Dokumentacja_JavaScript - - Dokumentacje - - JavaScript - - Strony_wymagające_dopracowania - - Wszystkie_kategorie -translation_of: Web/JavaScript/Reference/Statements/throw -original_slug: Web/JavaScript/Referencje/Polecenia/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/typed_arrays/index.html b/files/pl/web/javascript/typed_arrays/index.html deleted file mode 100644 index b36127886f..0000000000 --- a/files/pl/web/javascript/typed_arrays/index.html +++ /dev/null @@ -1,274 +0,0 @@ ---- -title: Tablice reprezentujące typy JavaScript -slug: Web/JavaScript/Typed_arrays -translation_of: Web/JavaScript/Typed_arrays ---- -
-
{{JsSidebar("Advanced")}}
-
- -

Jako, że aplikacje internetowe stają się coraz bardziej potężne, zapewniając takie możliwości jak chociażby manipulacja audio i wideo, dostęp do surowych danych używając WebSocket, i tak dalej, stało się jasne, że są sytuacje, w których przydałoby się, żeby kod JavaScript był w stanie szybko i łatwo manipulować surowymi danymi binarnymi. W przeszłości, musiało być to symulowane przez traktowanie surowych danych jako string i używanie metody charCodeAt(), aby przeczytać bajty z buforu danych.

- -

Jakkolwiek, jest to wolne i podatne na błędy, ze względu na potrzebę wielu konwersji (szczególnie jeśli dane binarne nie są tak naprawdę danymi w formacie bajtów, ale, na przykład, 32-bitowymi liczbami całkowitymi lub zmiennoprzecinkowymi).

- -

Tablice zawierające typy JavaScript zapewniają mechanizm dostępu do danych binarnych dużo bardziej wydajnie.

- - - - - - - - -
-

Dokumentacja

- -
-
ArrayBuffer
-
The ArrayBuffer is a data type that is used to represent a generic, fixed-length binary data buffer. You can't directly manipulate the contents of an ArrayBuffer; instead, you create an ArrayBufferView object which represents the buffer in a specific format, and use that to read and write the contents of the buffer.
-
ArrayBufferView
-
The ArrayBufferView type describes a particular view on the contents of an ArrayBuffer's data. Of note is that you may create multiple views into the same buffer, each looking at the buffer's contents starting at a particular offset. This makes it possible to set up views of different data types to read the contents of a buffer based on the types of data at specific offsets into the buffer
-
DataView
-
-

The DataView view provides a low-level interface for reading data from and writing it to an ArrayBuffer.

-
-
StringView Non native
-
In this article is published a library of ours whose aims are: -
    -
  • creating a C-like interface for strings (i.e. array of characters codes — an ArrayBufferView in JavaScript) based upon the JavaScript ArrayBuffer interface,
  • -
  • creating an highly scalable library, that anyone can extend by adding methods to the object StringView.prototype,
  • -
  • creating a collection of methods for such string-like objects (since now: stringViews) which work strictly on arrays of numbers rather than on creating new immutable JavaScript strings,
  • -
  • working with other Unicode encodings different from default JavaScript's UTF-16 {{domxref("DOMString")}}s,
  • -
-
-
Getting ArrayBuffers or typed arrays from Base64-encoded strings
-
Code snippets to get ArrayBuffers or typed arrays from Base64-encoded strings.
-
FileReader.prototype.readAsArrayBuffer()
-
The FileReader.prototype.readAsArrayBuffer() method starts reading the contents of the specified Blob or File.
-
XMLHttpRequest.prototype.send()
-
XMLHttpRequest instances' send() method now supports typed arrays and ArrayBuffers as argument.
-
- -
-

Społeczność

- -
    -
  • Zobacz forum Mozilla... {{ DiscussionList("dev-web-development", "mozilla.dev.web.development") }}
  • -
- -

Narzędzia

- - - - - - -
- -

Bufory i widoki: struktura tablic reprezentujących typy

- -

To achieve maximum flexibility and efficiency, JavaScript typed arrays split the implementation into a buffer and a view. A buffer (implemented by the ArrayBuffer class) is an object representing a chunk of data; it has no format to speak of, and offers no mechanism for accessing its contents. In order to access the memory contained in a buffer, you need to use a view. A view provides a context—that is, a data type, starting offset, and number of elements—that turns the data into an actual typed array. Views are implemented by the ArrayBufferView class and its subclasses.

- -

Podklasy tablic reprezentujących typy

- -

The following subclasses provide buffer views allowing access to the data in specific data types. Note that the classes that work with more than one byte (e.g. Int16Array) use the platform byte order. If control over byte order is needed, use DataView instead.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TypRozmiarOpisOdpowiednik C
Int8Array18-bitowa liczba całkowita ze znakiem w zapisie dopełnienia do dwóchsigned char
Uint8Array18-bitowa liczba całkowita bez znakuunsigned char
Uint8ClampedArray18-bitowa liczba całkowita bez znakuunsigned char
Int16Array216-bitowa liczba całkowita ze znakiem w zapisie dopełnienia do dwóchshort
Uint16Array216-bitowa liczba całkowita bez znakuunsigned short
Int32Array432-bitowa liczba całkowita ze znakiem w zapisie dopełnienia do dwóchint
Uint32Array432-bitowa liczba całkowita bez znakuunsigned int
Float32Array432-bitowa liczba zmiennoprzecinkowa IEEEfloat
Float64Array864-bitowa liczba zmiennoprzecinkowa IEEEdouble
- -

Superklasy tablic reprezentujących typy

- - - - - - - - - - - - - - - - -
TypOpis
DataViewThe DataView view provides a low-level interface for reading data from and writing it to an ArrayBuffer.
StringView Non nativeThe StringView view provides a C-like interface for strings (i.e. array of characters codes — an ArrayBufferView in JavaScript) based upon the JavaScript ArrayBuffer interface,
- -

Używanie widoków z buforami

- -

Stwórzmy 16-bajtowy bufor:

- -
var buffer = new ArrayBuffer(16);
-
- -

At this point, we have a chunk of memory whose bytes are all pre-initialized to 0. There's not a lot we can do with it, though. We can confirm that it is indeed 16 bytes long, and that's about it:

- -
if (buffer.byteLength == 16) {
-  alert("Yes, it's 16 bytes.");
-} else {
-  alert("Oh no, it's the wrong size!");
-}
-
- -

Before we can really work with this buffer, we need to create a view. Let's create a view that treats the data in the buffer as an array of 32-bit signed integers:

- -
var int32View = new Int32Array(buffer);
-
- -

Now we can access the fields in the array just like a normal array:

- -
for (var i=0; i<int32View.length; i++) {
-  int32View[i] = i*2;
-}
-
- -

This fills out the 4 entries in the array (4 entries at 4 bytes each makes 16 total bytes) with the values 0, 2, 4, and 6.

- -

Wiele widoków tych samych danych

- -

Things start to get really interesting when you consider that you can create multiple views onto the same data. For example, given the code above, we can continue like this:

- -
var int16View = new Int16Array(buffer);
-
-for (var i=0; i<int16View.length; i++) {
-  console.log("Entry " + i + ": " + int16View[i]);
-}
-
- -

Here we create a 16-bit integer view that shares the same buffer as the existing 32-bit view and we output all the values in the buffer as 16-bit integers. Now we get the output 0, 0, 2, 0, 4, 0, 6, 0.

- -

You can go a step farther, though. Consider this:

- -
int16View[0] = 32;
-console.log("Entry 0 in the 32-bit array is now " + int32View[0]);
-
- -

The output from this is "Entry 0 in the 32-bit array is now 32". In other words, the two arrays are indeed simply views on the same data buffer, treating it as different formats. You can do this with any view types.

- -

Praca ze złożonymi strukturami danych

- -

By combining a single buffer with multiple views of different types, starting at different offsets into the buffer, you can interact with data objects containing multiple data types. This lets you, for example, interact with complex data structures from WebGL, data files, or C structures you need to use while using js-ctypes.

- -

Rozważ tą strukturę C:

- -
struct someStruct {
-  unsigned long id;
-  char username[16];
-  float amountDue;
-};
- -

Możesz uzyskać dostęp do bufora zawierającego dane w tych formacie w ten sposób:

- -
var buffer = new ArrayBuffer(24);
-
-// ... zczytaj dane do bufora ...
-
-var idView = new Uint32Array(buffer, 0, 1);
-var usernameView = new Uint8Array(buffer, 4, 16);
-var amountDueView = new Float32Array(buffer, 20, 1);
- -

Potem możesz uzyskać dostęp, na przykład, do kwoty należnej używając amountDueView[0].

- -
Note: The data structure alignment in a C structure is platform-dependent. Take precautions and considerations for these padding differences.
- -

Konwersja do zwykłych tablic

- -

After processing a typed array, it is sometimes useful to convert it back to a normal array in order to benefit from the Array prototype. Following is a way to do that.

- -
var typedArray = new Uint8Array( [ 1, 2, 3, 4 ] ),
-    normalArray = Array.apply( [], typedArray );
-normalArray.length === 4;
-normalArray.constructor === Array;
-
- -

Kompatybilność

- -

Typed arrays are available in WebKit as well. Chrome 7 includes support for ArrayBuffer, Float32Array, Int16Array, and Uint8Array. Chrome 9 and Firefox 15 add support for DataView objects. Internet Explorer 10 supports all types except Uint8ClampedArray and ArrayBuffer.prototype.slice.

- -

Specyfikacja

- - - -

Zobacz także

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