From 074785cea106179cb3305637055ab0a009ca74f2 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:42:52 -0500 Subject: initial commit --- .../nl/web/javascript/reference/errors/index.html | 31 ++ .../reference/errors/not_defined/index.html | 70 +++ .../reference/errors/unexpected_token/index.html | 48 ++ .../web/javascript/reference/functions/index.html | 612 +++++++++++++++++++++ .../reference/functions/rest_parameters/index.html | 183 ++++++ .../global_objects/array/concat/index.html | 176 ++++++ .../global_objects/array/entries/index.html | 132 +++++ .../global_objects/array/every/index.html | 191 +++++++ .../reference/global_objects/array/fill/index.html | 142 +++++ .../global_objects/array/filter/index.html | 217 ++++++++ .../reference/global_objects/array/find/index.html | 224 ++++++++ .../global_objects/array/findindex/index.html | 177 ++++++ .../global_objects/array/includes/index.html | 220 ++++++++ .../reference/global_objects/array/index.html | 485 ++++++++++++++++ .../global_objects/array/indexof/index.html | 244 ++++++++ .../global_objects/array/isarray/index.html | 142 +++++ .../reference/global_objects/array/map/index.html | 324 +++++++++++ .../reference/global_objects/array/push/index.html | 179 ++++++ .../global_objects/array/shift/index.html | 110 ++++ .../global_objects/array/slice/index.html | 269 +++++++++ .../global_objects/array/splice/index.html | 177 ++++++ .../reference/global_objects/date/index.html | 266 +++++++++ .../global_objects/function/apply/index.html | 258 +++++++++ .../global_objects/function/call/index.html | 225 ++++++++ .../reference/global_objects/function/index.html | 236 ++++++++ .../javascript/reference/global_objects/index.html | 183 ++++++ .../reference/global_objects/isfinite/index.html | 95 ++++ .../reference/global_objects/null/index.html | 124 +++++ .../reference/global_objects/object/index.html | 226 ++++++++ .../global_objects/object/prototype/index.html | 240 ++++++++ .../reference/global_objects/parsefloat/index.html | 168 ++++++ .../reference/global_objects/string/index.html | 409 ++++++++++++++ .../global_objects/string/indexof/index.html | 200 +++++++ .../global_objects/string/startswith/index.html | 96 ++++ .../global_objects/string/tolowercase/index.html | 125 +++++ .../global_objects/string/touppercase/index.html | 125 +++++ .../global_objects/string/trim/index.html | 139 +++++ .../reference/global_objects/symbool/index.html | 205 +++++++ files/nl/web/javascript/reference/index.html | 50 ++ .../nl/web/javascript/reference/klasses/index.html | 252 +++++++++ .../web/javascript/reference/operatoren/index.html | 288 ++++++++++ .../reference/operatoren/typeof/index.html | 244 ++++++++ .../reference/statements/export/index.html | 155 ++++++ .../web/javascript/reference/statements/index.html | 149 +++++ .../reference/template_literals/index.html | 254 +++++++++ 45 files changed, 9065 insertions(+) create mode 100644 files/nl/web/javascript/reference/errors/index.html create mode 100644 files/nl/web/javascript/reference/errors/not_defined/index.html create mode 100644 files/nl/web/javascript/reference/errors/unexpected_token/index.html create mode 100644 files/nl/web/javascript/reference/functions/index.html create mode 100644 files/nl/web/javascript/reference/functions/rest_parameters/index.html create mode 100644 files/nl/web/javascript/reference/global_objects/array/concat/index.html create mode 100644 files/nl/web/javascript/reference/global_objects/array/entries/index.html create mode 100644 files/nl/web/javascript/reference/global_objects/array/every/index.html create mode 100644 files/nl/web/javascript/reference/global_objects/array/fill/index.html create mode 100644 files/nl/web/javascript/reference/global_objects/array/filter/index.html create mode 100644 files/nl/web/javascript/reference/global_objects/array/find/index.html create mode 100644 files/nl/web/javascript/reference/global_objects/array/findindex/index.html create mode 100644 files/nl/web/javascript/reference/global_objects/array/includes/index.html create mode 100644 files/nl/web/javascript/reference/global_objects/array/index.html create mode 100644 files/nl/web/javascript/reference/global_objects/array/indexof/index.html create mode 100644 files/nl/web/javascript/reference/global_objects/array/isarray/index.html create mode 100644 files/nl/web/javascript/reference/global_objects/array/map/index.html create mode 100644 files/nl/web/javascript/reference/global_objects/array/push/index.html create mode 100644 files/nl/web/javascript/reference/global_objects/array/shift/index.html create mode 100644 files/nl/web/javascript/reference/global_objects/array/slice/index.html create mode 100644 files/nl/web/javascript/reference/global_objects/array/splice/index.html create mode 100644 files/nl/web/javascript/reference/global_objects/date/index.html create mode 100644 files/nl/web/javascript/reference/global_objects/function/apply/index.html create mode 100644 files/nl/web/javascript/reference/global_objects/function/call/index.html create mode 100644 files/nl/web/javascript/reference/global_objects/function/index.html create mode 100644 files/nl/web/javascript/reference/global_objects/index.html create mode 100644 files/nl/web/javascript/reference/global_objects/isfinite/index.html create mode 100644 files/nl/web/javascript/reference/global_objects/null/index.html create mode 100644 files/nl/web/javascript/reference/global_objects/object/index.html create mode 100644 files/nl/web/javascript/reference/global_objects/object/prototype/index.html create mode 100644 files/nl/web/javascript/reference/global_objects/parsefloat/index.html create mode 100644 files/nl/web/javascript/reference/global_objects/string/index.html create mode 100644 files/nl/web/javascript/reference/global_objects/string/indexof/index.html create mode 100644 files/nl/web/javascript/reference/global_objects/string/startswith/index.html create mode 100644 files/nl/web/javascript/reference/global_objects/string/tolowercase/index.html create mode 100644 files/nl/web/javascript/reference/global_objects/string/touppercase/index.html create mode 100644 files/nl/web/javascript/reference/global_objects/string/trim/index.html create mode 100644 files/nl/web/javascript/reference/global_objects/symbool/index.html create mode 100644 files/nl/web/javascript/reference/index.html create mode 100644 files/nl/web/javascript/reference/klasses/index.html create mode 100644 files/nl/web/javascript/reference/operatoren/index.html create mode 100644 files/nl/web/javascript/reference/operatoren/typeof/index.html create mode 100644 files/nl/web/javascript/reference/statements/export/index.html create mode 100644 files/nl/web/javascript/reference/statements/index.html create mode 100644 files/nl/web/javascript/reference/template_literals/index.html (limited to 'files/nl/web/javascript/reference') diff --git a/files/nl/web/javascript/reference/errors/index.html b/files/nl/web/javascript/reference/errors/index.html new file mode 100644 index 0000000000..c295fccea6 --- /dev/null +++ b/files/nl/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/nl/web/javascript/reference/errors/not_defined/index.html b/files/nl/web/javascript/reference/errors/not_defined/index.html new file mode 100644 index 0000000000..9fb12d7937 --- /dev/null +++ b/files/nl/web/javascript/reference/errors/not_defined/index.html @@ -0,0 +1,70 @@ +--- +title: 'ReferenceError: "x" is not defined' +slug: Web/JavaScript/Reference/Errors/Not_defined +tags: + - Foutmelding + - JavaScript + - ReferenceError +translation_of: Web/JavaScript/Reference/Errors/Not_defined +--- +
{{jsSidebar("Errors")}}
+ +

Foutmelding

+ +
ReferenceError: "x" is not defined
+
+ +

Type fout

+ +

{{jsxref("ReferenceError")}}.

+ +

Wat is er fout gegaan?

+ +

Er is ergens een niet bestaande variabele genoemd. Deze variabele moet je declareren, of je moet er voor zorgen dat deze beschikbaar is in het script of {{Glossary("scope")}}.

+ +
+

Notitie: Wanneer je een library (zoals jQuery) laadt, zorg er dan voor dat die geladen is voordat je de library's variabelen wilt gebruiken, zoals "$". Zet de {{HTMLElement("script")}} tag die de library laadt, voor de code die de variabele gebruikt.

+
+ +

Voorbeelden

+ +

Variabele niet gedefineerd

+ +
foo.substring(1); // ReferenceError: foo is not defined
+
+ +

De "foo" variable is nergens gedefineerd. De variabele moet een string zijn, zodat de {{jsxref("String.prototype.substring()")}} method kan werken.

+ +
var foo = "bar";
+foo.substring(1); // "ar"
+ +

Verkeerde scope

+ +

Een variabele moet beschikbaar zijn in de huidige context of execution. Variabelen gedefineerd binnen een functie kunnen niet van ergens anders buiten de functie worden benarderd, omdat de variabele alleenmaar in de scope van de functie gedefineerd is

+ +
function numbers () {
+  var num1 = 2,
+      num2 = 3;
+  return num1 + num2;
+}
+
+console.log(num1); // ReferenceError num1 is not defined.
+ +

Maar, een functie kan alle andere variabelen benaderen in de scope waarin hij gedefineerd is. Oftewel, een functie die in de global scope is gedefineerd, kan alle variabelen benaderen in de global scope.

+ +
var num1 = 2,
+    num2 = 3;
+
+function numbers () {
+  return num1 + num2;
+}
+
+console.log(num1); // 2
+ +

Zie ook

+ + diff --git a/files/nl/web/javascript/reference/errors/unexpected_token/index.html b/files/nl/web/javascript/reference/errors/unexpected_token/index.html new file mode 100644 index 0000000000..264e8f5858 --- /dev/null +++ b/files/nl/web/javascript/reference/errors/unexpected_token/index.html @@ -0,0 +1,48 @@ +--- +title: 'SyntaxError: Onverwacht teken' +slug: Web/JavaScript/Reference/Errors/Unexpected_token +translation_of: Web/JavaScript/Reference/Errors/Unexpected_token +--- +
{{jsSidebar("Errors")}}
+ +

Boodschap

+ +
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"
+
+ +

type Error

+ +

{{jsxref("SyntaxError")}}

+ +

Wat ging er mis?

+ +

A specifieke taalconstructie werd verwacht, maar er werd iets anders geboden. Dit kan een simpele typfout zijn.

+ +

Er wordt een specifieke opbouw van de expressie verwacht, maar een andere werd "aangeboden". Het kan zijn dat een simpele typefout hiervan de oorzaak is.

+ +

Voorbeelden

+ +

Expression verwacht

+ +

Bijvoorbeeld, bij het uitvoeren van een functie zijn geen comma's toegelaten op het einde van de regel. JavaScript verwacht dan nog een argument dat in feite eender welke  expression kan zijn.

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

De juiste methode is om de comma te verwijderen of een bijkomend argument toe te voegen:

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

Zie ook

+ + diff --git a/files/nl/web/javascript/reference/functions/index.html b/files/nl/web/javascript/reference/functions/index.html new file mode 100644 index 0000000000..377a256fec --- /dev/null +++ b/files/nl/web/javascript/reference/functions/index.html @@ -0,0 +1,612 @@ +--- +title: Functions +slug: Web/JavaScript/Reference/Functions +tags: + - Function + - Functions + - JavaScript + - NeedsTranslation + - TopicStub +translation_of: Web/JavaScript/Reference/Functions +--- +
{{jsSidebar("Functions")}}
+ +

Generally speaking, a function is a "subprogram" that can be called by code external (or internal in the case of recursion) to the function. Like the program itself, a function is composed of a sequence of statements called the function body. Values can be passed to a function, and the function will return a value.

+ +

In JavaScript, functions are first-class objects, because they can have properties and methods just like any other object. What distinguishes them from other objects is that functions can be called. In brief, they are Function objects.

+ +

For more examples and explanations, see also the JavaScript guide about functions.

+ +

Description

+ +

Every function in JavaScript is a Function object. See {{jsxref("Function")}} for information on properties and methods of Function objects.

+ +

Functions are not the same as procedures. A function always returns a value, whereas a procedure might not.

+ +

To return a value other than the default, a function must have a return statement that specifies the value to return. A function without a return statement will return a default value. In the case of a constructor called with the new keyword, the default value is the value of its this parameter. For all other functions, the default return value is undefined.

+ +

The parameters of a function call are the function's arguments. Arguments are passed to functions by value. If the function changes the value of an argument, this change is not reflected globally or in the calling function. However, object references are values, too, and they are special: if the function changes the referred object's properties, that change is visible outside the function, as shown in the following example:

+ +
/* Declare the function 'myFunc' */
+function myFunc(theObject) {
+   theObject.brand = "Toyota";
+ }
+
+ /*
+  * Declare variable 'mycar';
+  * create and initialize a new Object;
+  * assign reference to it to 'mycar'
+  */
+ var mycar = {
+   brand: "Honda",
+   model: "Accord",
+   year: 1998
+ };
+
+ /* Logs 'Honda' */
+ console.log(mycar.brand);
+
+ /* Pass object reference to the function */
+ myFunc(mycar);
+
+ /*
+  * Logs 'Toyota' as the value of the 'brand' property
+  * of the object, as changed to by the function.
+  */
+ console.log(mycar.brand);
+
+ +

The this keyword does not refer to the currently executing function, so you must refer to Function objects by name, even within the function body.

+ +

Defining functions

+ +

There are several ways to define functions:

+ +

The function declaration (function statement)

+ +

There is a special syntax for declaring functions (see function statement for details):

+ +
function name([param[, param[, ... param]]]) {
+   statements
+}
+
+ +
+
name
+
The function name.
+
+ +
+
param
+
The name of an argument to be passed to the function. A function can have up to 255 arguments.
+
+ +
+
statements
+
The statements comprising the body of the function.
+
+ +

The function expression (function expression)

+ +

A function expression is similar to and has the same syntax as a function declaration (see function expression for details):

+ +
function [name]([param[, param[, ... param]]]) {
+   statements
+}
+
+ +
+
name
+
The function name. Can be omitted, in which case the function becomes known as an anonymous function.
+
+ +
+
param
+
The name of an argument to be passed to the function. A function can have up to 255 arguments.
+
statements
+
The statements comprising the body of the function.
+
+ +

The generator function declaration (function* statement)

+ +
+

Note: Generator functions are an experimental technology, part of the ECMAScript 6 proposal, and are not widely supported by browsers yet.

+
+ +

There is a special syntax for generator function declarations (see {{jsxref('Statements/function*', 'function* statement')}} for details):

+ +
function* name([param[, param[, ... param]]]) {
+   statements
+}
+
+ +
+
name
+
The function name.
+
+ +
+
param
+
The name of an argument to be passed to the function. A function can have up to 255 arguments.
+
+ +
+
statements
+
The statements comprising the body of the function.
+
+ +

The generator function expression (function* expression)

+ +
+

Note: Generator functions are an experimental technology, part of the ECMAScript 6 proposal, and are not widely supported by browsers yet.

+
+ +

A generator function expression is similar to and has the same syntax as a generator function declaration (see {{jsxref('Operators/function*', 'function* expression')}} for details):

+ +
function* [name]([param[, param[, ... param]]]) {
+   statements
+}
+
+ +
+
name
+
The function name. Can be omitted, in which case the function becomes known as an anonymous function.
+
+ +
+
param
+
The name of an argument to be passed to the function. A function can have up to 255 arguments.
+
statements
+
The statements comprising the body of the function.
+
+ +

The arrow function expression (=>)

+ +
+

Note: Arrow function expressions are an experimental technology, part of the ECMAScript 6 proposal, and are not widely supported by browsers yet.

+
+ +

An arrow function expression has a shorter syntax and lexically binds its this value (see arrow functions for details):

+ +
([param[, param]]) => {
+   statements
+}
+
+param => expression
+
+ +
+
param
+
The name of an argument. Zero arguments need to be indicated with ().  For only one argument, the parentheses are not required. (like foo => 1)
+
statements or expression
+
Multiple statements need to be enclosed in brackets. A single expression requires no brackets. The expression is also the implicit return value of the function.
+
+ +

The Function constructor

+ +
+

Note: Using the Function constructor to create functions is not recommended since it needs the function body as a string which may prevent some JS engine optimizations and can also cause other problems.

+
+ +

As all other objects, {{jsxref("Function")}} objects can be created using the new operator:

+ +
new Function (arg1, arg2, ... argN, functionBody)
+
+ +
+
arg1, arg2, ... argN
+
Zero or more names to be used by the function as formal parameters. Each must be a proper JavaScript identifier.
+
+ +
+
functionBody
+
A string containing the JavaScript statements comprising the function body.
+
+ +

Invoking the Function constructor as a function (without using the new operator) has the same effect as invoking it as a constructor.

+ +

The GeneratorFunction constructor

+ +
+

Note: Arrow function expressions are an experimental technology, part of the ECMAScript 6 proposal, and are not widely supported by browsers yet.

+
+ +
+

Note: GeneratorFunction is not a global object, but could be obtained from generator function instance (see {{jsxref("GeneratorFunction")}} for more detail).

+
+ +
+

Note: Using the GeneratorFunction constructor to create functions is not recommended since it needs the function body as a string which may prevent some JS engine optimizations and can also cause other problems.

+
+ +

As all other objects, {{jsxref("GeneratorFunction")}} objects can be created using the new operator:

+ +
new GeneratorFunction (arg1, arg2, ... argN, functionBody)
+
+ +
+
arg1, arg2, ... argN
+
Zero or more names to be used by the function as formal argument names. Each must be a string that conforms to the rules for a valid JavaScript identifier or a list of such strings separated with a comma; for example "x", "theValue", or "a,b".
+
+ +
+
functionBody
+
A string containing the JavaScript statements comprising the function definition.
+
+ +

Invoking the Function constructor as a function (without using the new operator) has the same effect as invoking it as a constructor.

+ +

Function parameters

+ +
+

Note: Default and rest parameters are experimental technology, part of the ECMAScript 6 proposal, and are not widely supported by browsers yet.

+
+ +

Default parameters

+ +

Default function parameters allow formal parameters to be initialized with default values if no value or undefined is passed. For more details, see default parameters.

+ +

Rest parameters

+ +

The rest parameter syntax allows to represent an indefinite number of arguments as an array. For more details, see rest parameters.

+ +

The arguments object

+ +

You can refer to a function's arguments within the function by using the arguments object. See arguments.

+ + + +

Defining method functions

+ +

Getter and setter functions

+ +

You can define getters (accessor methods) and setters (mutator methods) on any standard built-in object or user-defined object that supports the addition of new properties. The syntax for defining getters and setters uses the object literal syntax.

+ +
+
get
+
+

Binds an object property to a function that will be called when that property is looked up.

+
+
set
+
Binds an object property to a function to be called when there is an attempt to set that property.
+
+ +

Method definition syntax

+ +
+

Note: Method definitions are experimental technology, part of the ECMAScript 6 proposal, and are not widely supported by browsers yet.

+
+ +

Starting with ECMAScript 6, you are able to define own methods in a shorter syntax, similar to the getters and setters. See method definitions for more information.

+ +
var obj = {
+  foo() {},
+  bar() {}
+};
+ +

Function constructor vs. function declaration vs. function expression

+ +

Compare the following:

+ +

A function defined with the Function constructor assigned to the variable multiply:

+ +
function multiply(x, y) {
+   return x * y;
+}
+
+ +

A function expression of an anonymous function assigned to the variable multiply:

+ +
var multiply = function(x, y) {
+   return x * y;
+};
+
+ +

A function expression of a function named func_name assigned to the variable multiply:

+ +
var multiply = function func_name(x, y) {
+   return x * y;
+};
+
+ +

Differences

+ +

All do approximately the same thing, with a few subtle differences:

+ +

There is a distinction between the function name and the variable the function is assigned to. The function name cannot be changed, while the variable the function is assigned to can be reassigned. The function name can be used only within the function's body. Attempting to use it outside the function's body results in an error (or undefined if the function name was previously declared via a var statement). For example:

+ +
var y = function x() {};
+alert(x); // throws an error
+
+ +

The function name also appears when the function is serialized via Function's toString method.

+ +

On the other hand, the variable the function is assigned to is limited only by its scope, which is guaranteed to include the scope where the function is declared in.

+ +

As the 4th example shows, the function name can be different from the variable the function is assigned to. They have no relation to each other.A function declaration also creates a variable with the same name as the function name. Thus, unlike those defined by function expressions, functions defined by function declarations can be accessed by their name in the scope they were defined in:

+ +

A function defined by 'new Function' does not have a function name. However, in the SpiderMonkey JavaScript engine, the serialized form of the function shows as if it has the name "anonymous". For example, alert(new Function()) outputs:

+ +
function anonymous() {
+}
+
+ +

Since the function actually does not have a name, anonymous is not a variable that can be accessed within the function. For example, the following would result in an error:

+ +
var foo = new Function("alert(anonymous);");
+foo();
+
+ +

Unlike functions defined by function expressions or by the Function constructor, a function defined by a function declaration can be used before the function declaration itself. For example:

+ +
foo(); // alerts FOO!
+function foo() {
+   alert('FOO!');
+}
+
+ +

A function defined by a function expression inherits the current scope. That is, the function forms a closure. On the other hand, a function defined by a Function constructor does not inherit any scope other than the global scope (which all functions inherit).

+ +

Functions defined by function expressions and function declarations are parsed only once, while those defined by the Function constructor are not. That is, the function body string passed to the Function constructor must be parsed each and every time the constructor is called. Although a function expression creates a closure every time, the function body is not reparsed, so function expressions are still faster than "new Function(...)". Therefore the Function constructor should generally be avoided whenever possible.

+ +

It should be noted, however, that function expressions and function declarations nested within the function generated by parsing a Function constructor 's string aren't parsed repeatedly. For example:

+ +
var foo = (new Function("var bar = \'FOO!\';\nreturn(function() {\n\talert(bar);\n});"))();
+foo(); // The segment "function() {\n\talert(bar);\n}" of the function body string is not re-parsed.
+ +

A function declaration is very easily (and often unintentionally) turned into a function expression. A function declaration ceases to be one when it either:

+ + + +
var x = 0;               // source element
+if (x == 0) {            // source element
+   x = 10;               // not a source element
+   function boo() {}     // not a source element
+}
+function foo() {         // source element
+   var y = 20;           // source element
+   function bar() {}     // source element
+   while (y == 10) {     // source element
+      function blah() {} // not a source element
+      y++;               // not a source element
+   }
+}
+
+ +

Examples

+ +
// function declaration
+function foo() {}
+
+// function expression
+(function bar() {})
+
+// function expression
+x = function hello() {}
+
+
+if (x) {
+   // function expression
+   function world() {}
+}
+
+
+// function declaration
+function a() {
+   // function declaration
+   function b() {}
+   if (0) {
+      // function expression
+      function c() {}
+   }
+}
+
+ +

Conditionally defining a function

+ +

Functions can be conditionally defined using either //function statements// (an allowed extension to the ECMA-262 Edition 3 standard) or the Function constructor. Please note that such function statements are no longer allowed in ES5 strict. Additionally, this feature does not work consistently cross-browser, so you should not rely on it.

+ +

In the following script, the zero function is never defined and cannot be invoked, because 'if (0)' evaluates its condition to false:

+ +
if (0) {
+   function zero() {
+      document.writeln("This is zero.");
+   }
+}
+
+ +

If the script is changed so that the condition becomes 'if (1)', function zero is defined.

+ +

Note: Although this kind of function looks like a function declaration, it is actually an expression (or statement), since it is nested within another statement. See differences between function declarations and function expressions.

+ +

Note: Some JavaScript engines, not including SpiderMonkey, incorrectly treat any function expression with a name as a function definition. This would lead to zero being defined, even with the always-false if condition. A safer way to define functions conditionally is to define the function anonymously and assign it to a variable:

+ +
if (0) {
+   var zero = function() {
+      document.writeln("This is zero.");
+   }
+}
+
+ +

Examples

+ +

Returning a formatted number

+ +

The following function returns a string containing the formatted representation of a number padded with leading zeros.

+ +
// This function returns a string padded with leading zeros
+function padZeros(num, totalLen) {
+   var numStr = num.toString();             // Initialize return value as string
+   var numZeros = totalLen - numStr.length; // Calculate no. of zeros
+   for (var i = 1; i <= numZeros; i++) {
+      numStr = "0" + numStr;
+   }
+   return numStr;
+}
+
+ +

The following statements call the padZeros function.

+ +
var result;
+result = padZeros(42,4); // returns "0042"
+result = padZeros(42,2); // returns "42"
+result = padZeros(5,4);  // returns "0005"
+
+ +

Determining whether a function exists

+ +

You can determine whether a function exists by using the typeof operator. In the following example, a test is peformed to determine if the window object has a property called noFunc that is a function. If so, it is used; otherwise some other action is taken.

+ +
 if ('function' == typeof window.noFunc) {
+   // use noFunc()
+ } else {
+   // do something else
+ }
+
+ +

Note that in the if test, a reference to noFunc is used—there are no brackets "()" after the function name so the actual function is not called.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0
{{SpecName('ES5.1', '#sec-13', 'Function Definition')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-function-definitions', 'Function definitions')}}{{Spec2('ES6')}}New: Arrow functions, Generator functions, default parameters, rest parameters.
{{SpecName('ESDraft', '#sec-function-definitions', 'Function definitions')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Generator function39{{CompatGeckoDesktop("26.0")}}{{CompatUnknown}}26{{CompatUnknown}}
Arrow function{{CompatNo}}{{CompatGeckoDesktop("22.0")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Generator function{{CompatUnknown}}39{{CompatGeckoMobile("26.0")}}{{CompatUnknown}}26{{CompatUnknown}}
Arrow function{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile("22.0")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

See also

+ + diff --git a/files/nl/web/javascript/reference/functions/rest_parameters/index.html b/files/nl/web/javascript/reference/functions/rest_parameters/index.html new file mode 100644 index 0000000000..e4c2acae46 --- /dev/null +++ b/files/nl/web/javascript/reference/functions/rest_parameters/index.html @@ -0,0 +1,183 @@ +--- +title: Rest parameters +slug: Web/JavaScript/Reference/Functions/rest_parameters +translation_of: Web/JavaScript/Reference/Functions/rest_parameters +--- +
{{jsSidebar("Functions")}}
+ +

De rest parameter syntax laat ons toe om een onbepaald aantal argumenten te vertegenwoordigen als een array.

+ +

Syntax

+ +
function(a, b, ...theArgs) {
+  // ...
+}
+
+ +

Beschrijving

+ +

Als het laatst genoemd argument van een functie wordt voorafgegaan door ..., dan wordt dit een array waarvan de elementen van 0 tot theArgs.length worden doorgegeven als eigenlijke argumenten aan de functie.

+ +

In het bovestaande voorbeeld, verzameld theArgs als derde argument van de functie. Alle opeenvolgende argumenten die na a en b zijn toegevoegd in de argumenten lijst.

+ +

Verschillen tussen de rest parameter en het arguments object

+ +

Er zijn drie belangrijke verschillen tussen de rest parameters en het arguments object:

+ + + +

Van arguments tot een array

+ +

Rest parameters zijn ingevoerd om de standaardcode die werd veroorzaakt door het arguments object te verminderen.

+ +
// Voor rest parameters, kwam je het volgende wel eens tegen:
+function f(a, b){
+  var args = Array.prototype.slice.call(arguments, f.length);
+
+  // …
+}
+
+// Wat net hetzelfde is als:
+
+function f(a, b, ...args) {
+
+}
+
+ +

Voorbeelden

+ +

Aangezien theArgs een array is, kunt u de telling van de elementen verkrijgen met het behulp van de eigenschap .length:

+ +
function fun1(...theArgs) {
+  console.log(theArgs.length);
+}
+
+fun1();  // 0
+fun1(5); // 1
+fun1(5, 6, 7); // 3
+
+ +

In het volgende voorbeeld, gebruiken we de rest parameter voor het verzamelen vanaf het tweede argument tot het einde. We vermenigvuldigen deze vervolgens met de eerste:

+ +
function multiply(multiplier, ...theArgs) {
+  return theArgs.map(function (element) {
+    return multiplier * element;
+  });
+}
+
+var arr = multiply(2, 1, 2, 3);
+console.log(arr); // [2, 4, 6]
+
+ +

Het volgende voorbeeld toont aan dat je Array methodes kan gebruiken op rest parameters maar niet op het arguments object:

+ +
function sortRestArgs(...theArgs) {
+  var sortedArgs = theArgs.sort();
+  return sortedArgs;
+}
+
+console.log(sortRestArgs(5,3,7,1)); // toont 1,3,5,7
+
+function sortArguments() {
+  var sortedArgs = arguments.sort();
+  return sortedArgs; // dit zal nooit gebeuren
+}
+
+// gooit een TypeError: arguments.sort is not a function
+console.log(sortArguments(5,3,7,1));
+
+ +

Om Array methodes op het arguments object te gebruiken, moet je het eerst converteren naar een echte array.

+ +

Specificatie

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES6', '#sec-function-definitions', 'Function Definitions')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-function-definitions', 'Function Definitions')}}{{Spec2('ESDraft')}}
+ +

Browser compatibiliteit

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome(47)}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("15.0")}}{{CompatNo}}34{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatChrome(47)}}{{CompatGeckoMobile("15.0")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatChrome(47)}}
+
+ +

Bekijk ook

+ + diff --git a/files/nl/web/javascript/reference/global_objects/array/concat/index.html b/files/nl/web/javascript/reference/global_objects/array/concat/index.html new file mode 100644 index 0000000000..b224c3fe3d --- /dev/null +++ b/files/nl/web/javascript/reference/global_objects/array/concat/index.html @@ -0,0 +1,176 @@ +--- +title: Array.prototype.concat() +slug: Web/JavaScript/Reference/Global_Objects/Array/concat +tags: + - Array + - JavaScript + - Methode(2) + - Prototype +translation_of: Web/JavaScript/Reference/Global_Objects/Array/concat +--- +
{{JSRef}}
+ +

De concat() methode geeft een nieuwe array terug bestaande uit de array waarop het is aangeroepen samengevoegd met de array(s) en/of waarden die zijn geleverd als argumenten.

+ +

Syntax

+ +
var nieuwe_array = oude_array.concat(waarde1[, waarde2[, ...[, waardeN]]])
+ +

Parameters

+ +
+
waardeN
+
Arrays en/of waarden om te concateneren in een nieuwe array. Zie de beschrijving voor details.
+
+ +

Returnwaarde

+ +

Een nieuwe instantie van type {{jsxref("Array")}}.

+ +

Beschrijving

+ +

concat maakt een nieuwe array bestaande uit de elementen in het object waarop het is aangeroepen, gevolgd door voor ieder argument de elementen van dat argument (als het argument een array is) of het argument zelf (als het argument geen array is).

+ +

concat verandert this niet en ook niet de als argument gegeven arrays, maar levert in plaats daarvan een shallow copy welke kopieën bevat van dezelfde elementen gecombineerd van de orginele arrays. Elementen van de orginele arrays worden als volgt gekopiëerd in de nieuwe array:

+ + + +
+

Opmerking: Concateneren van array(s)/waarde(n) laat de orginelen onaangetast. Bovendien zal iedere operatie op de nieuwe array geen effect hebben op de orginele array en vice versa.

+
+ +

Voorbeelden

+ +

Concateneren van twee arrays

+ +

De volgende code concateneert twee arrays

+ +
var alfa = ['a', 'b', 'c'],
+    nummer = [1, 2, 3];
+
+var alfaNummeriek = alfa.concat( nummer );
+
+console.log(alfaNummeriek); // Resultaat: ['a', 'b', 'c', 1, 2, 3]
+
+ +

Concateneren van drie arrays

+ +

De volgende code concateneert drie arrays

+ +
var num1 = [1, 2, 3],
+    num2 = [4, 5, 6],
+    num3 = [7, 8, 9];
+
+var nums = num1.concat(num2, num3);
+
+console.log(nums); // Resultaat: [1, 2, 3, 4, 5, 6, 7, 8, 9]
+
+ +

Concateneren van waarden naar een array

+ +

De volgende code concateneert drie waarden naar een array:

+ +
var alfa = ['a', 'b', 'c'];
+
+var alfaNumeriek =  alfa.concat(1, [2, 3]);
+
+console.log( alfaNumeriek);
+// Resultaat: ['a', 'b', 'c', 1, 2, 3]
+
+ +

Specificaties

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificatieStatusOpmerking
{{SpecName('ES3')}}{{Spec2('ES3')}}Eerste definitie. Geïmplementeerd in JavaScript 1.2.
{{SpecName('ES5.1', '#sec-15.4.4.4', 'Array.prototype.concat')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-array.prototype.concat', 'Array.prototype.concat')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.prototype.concat', 'Array.prototype.concat')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibiliteit

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basis support{{CompatChrome("1.0")}}{{CompatGeckoDesktop("1.7")}}{{CompatIE("5.5")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basis support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Zie ook

+ + diff --git a/files/nl/web/javascript/reference/global_objects/array/entries/index.html b/files/nl/web/javascript/reference/global_objects/array/entries/index.html new file mode 100644 index 0000000000..add0b7439a --- /dev/null +++ b/files/nl/web/javascript/reference/global_objects/array/entries/index.html @@ -0,0 +1,132 @@ +--- +title: Array.prototype.entries() +slug: Web/JavaScript/Reference/Global_Objects/Array/entries +tags: + - Array + - ECMAScript 2015 + - Iterator + - JavaScript + - Méthode + - Prototype +translation_of: Web/JavaScript/Reference/Global_Objects/Array/entries +--- +
{{JSRef}}
+ +

De entries() funtie geeft een nieuw Array Iterator object dat de key/value paren bevat voor elk onderdeel van de array.

+ +
var a = ['a', 'b', 'c'];
+var iterator = a.entries();
+
+console.log(iterator.next().value); // [0, 'a']
+console.log(iterator.next().value); // [1, 'b']
+console.log(iterator.next().value); // [2, 'c']
+
+ +

Syntax

+ +
a.entries()
+ +

Return waarde

+ +

Een nieuw {{jsxref("Array")}} iterator object.

+ +

Voorbeelden

+ +

De for…of loop

+ +
var a = ['a', 'b', 'c'];
+var iterator = a.entries();
+
+for (let e of iterator) {
+  console.log(e);
+}
+// [0, 'a']
+// [1, 'b']
+// [2, 'c']
+
+ +

Specificaties

+ + + + + + + + + + + + + + + + + + + +
SpecificatieStatusOpmerkingen
{{SpecName('ES6', '#sec-array.prototype.entries', 'Array.prototype.entries')}}{{Spec2('ES6')}}Standaard definitie.
{{SpecName('ESDraft', '#sec-array.prototype.entries', 'Array.prototype.entries')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibiliteit

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FunctieChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basis ondersteuning{{CompatChrome("38")}}{{CompatGeckoDesktop("28")}}{{CompatNo}}{{CompatOpera("25")}}{{CompatSafari("7.1")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FunctieAndroidChrome voor AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basis ondersteuning{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile("28")}}{{CompatNo}}{{CompatNo}}8.0
+
+ +

Zie ook

+ + diff --git a/files/nl/web/javascript/reference/global_objects/array/every/index.html b/files/nl/web/javascript/reference/global_objects/array/every/index.html new file mode 100644 index 0000000000..36834fec57 --- /dev/null +++ b/files/nl/web/javascript/reference/global_objects/array/every/index.html @@ -0,0 +1,191 @@ +--- +title: Array.prototype.every() +slug: Web/JavaScript/Reference/Global_Objects/Array/every +tags: + - Array + - ECMAScript 5 + - JavaScript + - Méthode + - Prototype + - polyfill +translation_of: Web/JavaScript/Reference/Global_Objects/Array/every +--- +
{{JSRef}}
+ +

De every() methode controleert of alle elementen in de array slagen voor de test die opgelegd wordt in de opgegeven functie.

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

Syntax

+ +
arr.every(callback[, thisArg])
+ +

Parameters

+ +
+
callback
+
Functie die elk element checkt, gebruikt 3 argumenten: +
+
currentValue (verplicht)
+
Het huidige element wat wordt verwerkt in het array.
+
index (optioneel)
+
De index van het huidige element wat wordt verwerkt in het array.
+
array (optioneel)
+
Het array waarop de methode every werd aangeroepen.
+
+
+
thisArg
+
Optioneel. Deze waarde wordt gebruikt als this wanneer callback wordt uitgevoerd.
+
+ +

Return value

+ +

true als de callback functie een {{Glossary("truthy")}} waarde terug geeft voor elk element uit het array; anders, false.

+ +

Beschrijving

+ +

De every methode voert voor elk element in het array de callback functie uit tot een element een {{Glossary("falsy")}} waarde teruggeeft. Wanneer een element met deze waarde gevonden wordt, geeft de every methode gelijk false terug. Als callback een {{Glossary("truthy")}} terug geeft voor alle elementen in het array zal every true terug geven. callback wordt alleen aangeroepen voor elementen in het array met een waarde; het wordt niet aangeroepen voor elementen die zijn gedeleted of nooit een waarde hebben gekregen.

+ +

callback wordt aangeroepen met 3 argumenten: de waarde van het element, de index van het element, en het Array object dat wordt doorlopen.

+ +

Wanneer een thisArg parameter wordt meegegeven aan every zal dit gebruikt worden als de this waarde van de callback. Indien dit niet wordt meegeven wordt undefined gebruikt als this waarde. De voor de callback uiteindelijk gebruikte this waarde wordt bepaald volgens de normale regels om this te bepalen voor een functie.

+ +

every verandert het array waarop het wordt aangeroepen niet.

+ +

De set van elementen die verwerkt zal worden door every wordt bepaald voor de eerste aanroep van callback. Elementen die na het aanroepen van every worden toegevoegd aan het array zullen niet door callback worden bezocht. Als bestaande elementen in het array worden gewijzigd zal de waarde die naar de callback gestuurd wordt de waarde zijn zoals deze was toen every aangeroepen werd; verwijderde elementen worden niet bezocht door callback.

+ +

every werkt als een "voor alle" kwantor in de wiskunde en de logica. In het bijzonder voor een lege array, hier wordt true terug gegeven. (Het is "vacuously true" dat alle element van een lege set voldoen aan welke gegeven conditie dan ook.)

+ +

Voorbeelden

+ +

Test grootte van alle array elementen

+ +

Het volgende voorbeeld checkt of alle elementen in het array groter zijn dan 10.

+ +
function isBigEnough(element, index, array) {
+  return element >= 10;
+}
+[12, 5, 8, 130, 44].every(isBigEnough);   // false
+[12, 54, 18, 130, 44].every(isBigEnough); // true
+
+ +

Met arrow functies

+ +

Arrow functions geven een kortere syntax voor dezelfde check.

+ +
[12, 5, 8, 130, 44].every(x => x >= 10); // false
+[12, 54, 18, 130, 44].every(x => x >= 10); // true
+ +

Polyfill

+ +

every is vanaf de 5e editie toegevoegd aan de ECMA-262 standaard; hierdoor is het mogelijk niet aanwezig in andere implementies van de standaard. Je kunt hier omheen werken door de volgende code toe te voegen aan je script. Hiermee geef je every de mogelijkheid om gebruikt te worden in implementaties die dat in beginsel niet ondersteunen. Dit algoritme is gelijk aan het algoritme in ECMS-262, 5e editie. Hierbij moet er van uit gegaan worden dat Object en TypeError hun originele waarde hebben en dat callbackfn.call de originele waarde van {{jsxref("Function.prototype.call")}} checkt.

+ +
if (!Array.prototype.every) {
+  Array.prototype.every = function(callbackfn, thisArg) {
+    'use strict';
+    var T, k;
+
+    if (this == null) {
+      throw new TypeError('this is null or not defined');
+    }
+
+    // 1. Let O be the result of calling ToObject passing the this
+    //    value as the argument.
+    var O = Object(this);
+
+    // 2. Let lenValue be the result of calling the Get internal method
+    //    of O with the argument "length".
+    // 3. Let len be ToUint32(lenValue).
+    var len = O.length >>> 0;
+
+    // 4. If IsCallable(callbackfn) is false, throw a TypeError exception.
+    if (typeof callbackfn !== 'function') {
+      throw new TypeError();
+    }
+
+    // 5. If thisArg was supplied, let T be thisArg; else let T be undefined.
+    if (arguments.length > 1) {
+      T = thisArg;
+    }
+
+    // 6. Let k be 0.
+    k = 0;
+
+    // 7. Repeat, while k < len
+    while (k < len) {
+
+      var kValue;
+
+      // a. Let Pk be ToString(k).
+      //   This is implicit for LHS operands of the in operator
+      // b. Let kPresent be the result of calling the HasProperty internal
+      //    method of O with argument Pk.
+      //   This step can be combined with c
+      // c. If kPresent is true, then
+      if (k in O) {
+
+        // i. Let kValue be the result of calling the Get internal method
+        //    of O with argument Pk.
+        kValue = O[k];
+
+        // ii. Let testResult be the result of calling the Call internal method
+        //     of callbackfn with T as the this value and argument list
+        //     containing kValue, k, and O.
+        var testResult = callbackfn.call(T, kValue, k, O);
+
+        // iii. If ToBoolean(testResult) is false, return false.
+        if (!testResult) {
+          return false;
+        }
+      }
+      k++;
+    }
+    return true;
+  };
+}
+
+ +

Specificaties

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificatieStatusOpmerking
{{SpecName('ES5.1', '#sec-15.4.4.16', 'Array.prototype.every')}}{{Spec2('ES5.1')}}Initiele definitie. Geimplementeerd in JavaScript 1.6.
{{SpecName('ES6', '#sec-array.prototype.every', 'Array.prototype.every')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.prototype.every', 'Array.prototype.every')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ +
+ + +

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

+
+ +

Zie ook

+ + diff --git a/files/nl/web/javascript/reference/global_objects/array/fill/index.html b/files/nl/web/javascript/reference/global_objects/array/fill/index.html new file mode 100644 index 0000000000..205f12011a --- /dev/null +++ b/files/nl/web/javascript/reference/global_objects/array/fill/index.html @@ -0,0 +1,142 @@ +--- +title: Array.prototype.fill() +slug: Web/JavaScript/Reference/Global_Objects/Array/fill +tags: + - Functies +translation_of: Web/JavaScript/Reference/Global_Objects/Array/fill +--- +
{{JSRef}}
+ +

De fill() functie verandert alle elementen in een array naar statische waarde. Vanaf de eerste index (standaard 0) tot de laatste index (standaard array.length). De functie geeft de aangepaste array terug.

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

Syntax

+ +
arr.fill(value[, start[, end]])
+
+ +

Parameters

+ +
+
value
+
Waarde om de array mee te vullen. (Let op, alle elementen in de array krijgen exact deze waarde.)
+
start {{optional_inline}}
+
Start index, standaard 0.
+
end {{optional_inline}}
+
Laatste index, standaard arr.length.
+
+ +

Return waarde

+ +

De aangepaste array, gevuld met value.

+ +

Description

+ + + +

Polyfill

+ +
if (!Array.prototype.fill) {
+  Object.defineProperty(Array.prototype, 'fill', {
+    value: function(value) {
+
+      // Steps 1-2.
+      if (this == null) {
+        throw new TypeError('this is null or not defined');
+      }
+
+      var O = Object(this);
+
+      // Steps 3-5.
+      var len = O.length >>> 0;
+
+      // Steps 6-7.
+      var start = arguments[1];
+      var relativeStart = start >> 0;
+
+      // Step 8.
+      var k = relativeStart < 0 ?
+        Math.max(len + relativeStart, 0) :
+        Math.min(relativeStart, len);
+
+      // Steps 9-10.
+      var end = arguments[2];
+      var relativeEnd = end === undefined ?
+        len : end >> 0;
+
+      // Step 11.
+      var finalValue = relativeEnd < 0 ?
+        Math.max(len + relativeEnd, 0) :
+        Math.min(relativeEnd, len);
+
+      // Step 12.
+      while (k < finalValue) {
+        O[k] = value;
+        k++;
+      }
+
+      // Step 13.
+      return O;
+    }
+  });
+}
+
+ +

Als verouderde JavaScript engines ondersteund moeten worden, welke Object.defineProperty   niet ondersteunen, dan is het beter om helemaal geen polyfill Array.prototype functies te gebruiken, aangezien ze dan niet non-enumerable te maken zijn.

+ +

Voorbeelden

+ +

Fill toepassen

+ +
[1, 2, 3].fill(4)                // [4, 4, 4]
+[1, 2, 3].fill(4, 1)             // [1, 4, 4]
+[1, 2, 3].fill(4, 1, 2)          // [1, 4, 3]
+[1, 2, 3].fill(4, 1, 1)          // [1, 2, 3]
+[1, 2, 3].fill(4, 3, 3)          // [1, 2, 3]
+[1, 2, 3].fill(4, -3, -2)        // [4, 2, 3]
+[1, 2, 3].fill(4, NaN, NaN)      // [1, 2, 3]
+[1, 2, 3].fill(4, 3, 5)          // [1, 2, 3]
+Array(3).fill(4)                 // [4, 4, 4]
+[].fill.call({ length: 3 }, 4)   // {0: 4, 1: 4, 2: 4, length: 3}
+
+// Een enkel object, waaraan door iedere positie in de array gerefereerd wordt:
+let arr = Array(3).fill({}) // [{}, {}, {}]
+arr[0].hi = "hi"            // [{ hi: "hi" }, { hi: "hi" }, { hi: "hi" }]
+
+ +

Specificaties

+ + + + + + + + + + +
Specificatie
{{SpecName('ESDraft', '#sec-array.prototype.fill', 'Array.prototype.fill')}}
+ +

Browser compatibiliteit

+ +
+ + +

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

+
+ +

Zie ook

+ + diff --git a/files/nl/web/javascript/reference/global_objects/array/filter/index.html b/files/nl/web/javascript/reference/global_objects/array/filter/index.html new file mode 100644 index 0000000000..433300acaa --- /dev/null +++ b/files/nl/web/javascript/reference/global_objects/array/filter/index.html @@ -0,0 +1,217 @@ +--- +title: Array.prototype.filter() +slug: Web/JavaScript/Reference/Global_Objects/Array/filter +translation_of: Web/JavaScript/Reference/Global_Objects/Array/filter +--- +
{{JSRef}}
+ +

De filter() method maakt een nieuwe array aan met enkel die elementen die de test doorstaan van een functie naar keuze.

+ +

Syntax

+ +
var new_array = arr.filter(callback[, thisArg])
+ +

Parameters

+ +
+
callback
+
Functie, onderwerpt ieder element aan een test. Wordt aangeroepen met argumenten (element, index, array). Levert als resultaat de waarde true om het element te behouden, of anders false.
+
thisArg
+
Optioneel. Te gebruiken als de this waarde, wanneer een callback wordt uitgevoerd.
+
+ +

Beschrijving

+ +

filter() roept een geleverde callback functie één keer aan voor ieder element van een array en maakt een nieuwe array aan met alle waarden waarvoor de callback een waarde welke kan worden omgezet naar true (truthy values) retourneert. callback wordt alleen aangeroepen voor indices van de array, welke een waarde bezitten; deze wordt niet gebruikt voor indices welke zijn verwijderd, of welke nooit een waarde hebben verkregen. Array elements die niet de callback test doorstaan, worden simpelweg overgeslagen en worden niet in de nieuwe array opgenomen.

+ +

callback wordt aangeroepen met drie argumenten:

+ +
    +
  1. de waarde (value) van het element
  2. +
  3. de index van het element
  4. +
  5. het Array object dat wordt veranderd
  6. +
+ +

Wanneer een thisArg parameter wordt toegevoegd aan filter, zal deze worden doorgegeven aan callback wanneer deze wordt aangeroepen, om gebruikt te worden als this waarde. In het andere geval zal de waarde undefined worden gebruikt als  this waarde. De this waarde, uiteindelijk zichtbaar in callback wordt bepaald door de gebruikelijke regels om de this waarde te bepalen voor een functie.

+ +

filter() verandert de array zelf niet, van waaruit deze als method wordt aangeroepen.

+ +

De reeks (range) van elementen welke door filter() onderhanden wordt genomen, wordt al voor de eerste aanroep van callback bepaald. Elementen, die aan de originele array worden toegevoegd nadat de filter() method was aangeroepen, zullen niet worden onderworpen aan callback. Indien bestaande elementen worden gewijzigd, of verwijderd, dan zal hun waarde, zoals overgedragen aan callback, de waarde zijn als die is, op het moment dat filter() ze bezoekt; elementen die worden verwijderd worden ook niet in behandeling genomen.

+ +

Voorbeelden

+ +

Filter lage waarden

+ +

Het volgende voorbeeld gebruikt filter() om een gefilterde array aan te maken, waarbij alle waarden onder de 10 zijn verwijderd.

+ +
function isBigEnough(value) {
+  return value >= 10;
+}
+var filtered = [12, 5, 8, 130, 44].filter(isBigEnough);
+// filtered is [12, 130, 44]
+
+ +

Filter foutieve items van JSON

+ +

Het volgende voorbeeld gebruikten filter() voor een gefilterde json van alle elementen met een numerieke id.

+ +
var arr = [
+  { id: 15 },
+  { id: -1 },
+  { id: 0 },
+  { id: 3 },
+  { id: 12.2 },
+  { },
+  { id: null },
+  { id: NaN },
+  { id: 'undefined' }
+];
+
+var invalidEntries = 0;
+
+function filterByID(obj) {
+  if ('id' in obj && typeof(obj.id) === 'number' && !isNaN(obj.id)) {
+    return true;
+  } else {
+    invalidEntries++;
+    return false;
+  }
+}
+
+var arrByID = arr.filter(filterByID);
+
+console.log('Gefilterde Array\n', arrByID);
+// Gefilterde Array
+// [{ id: 15 }, { id: -1 }, { id: 0 }, { id: 3 }, { id: 12.2 }]
+
+console.log('Number of Invalid Entries = ', invalidEntries);
+// Number of Invalid Entries = 4
+
+ +

Polyfill

+ +

filter() werd toegevoegd aan de  ECMA-262 standaard in de 5de editie; als deze kan het zijn dat deze niet in alle toepassingen van de standaard voorkomt. Als alternatief kun je de volgende code aan het begin van je scripts zetten, waardoor het gebruik van filter() word toegestaan binnen ECMA-262 implementaties, die dit nog niet van nature ondersteunen. Het algoritme is precies die, zoals gespecificeerd in  ECMA-262, 5de editie, aangenomen dat fn.call resulteert in de beginwaarde van  {{jsxref("Function.prototype.call()")}}, en dat {{jsxref("Array.prototype.push()")}} nog zijn originele waarde heeft.

+ +
if (!Array.prototype.filter) {
+  Array.prototype.filter = function(fun/*, thisArg*/) {
+    'use strict';
+
+    if (this === void 0 || this === null) {
+      throw new TypeError();
+    }
+
+    var t = Object(this);
+    var len = t.length >>> 0;
+    if (typeof fun !== 'function') {
+      throw new TypeError();
+    }
+
+    var res = [];
+    var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
+    for (var i = 0; i < len; i++) {
+      if (i in t) {
+        var val = t[i];
+
+        // NOTE: Technically this should Object.defineProperty at
+        //       the next index, as push can be affected by
+        //       properties on Object.prototype and Array.prototype.
+        //       But that method's new, and collisions should be
+        //       rare, so use the more-compatible alternative.
+        if (fun.call(thisArg, val, i, t)) {
+          res.push(val);
+        }
+      }
+    }
+
+    return res;
+  };
+}
+
+ +

Specificaties

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificatieStatusCommentaar
{{SpecName('ES5.1', '#sec-15.4.4.20', 'Array.prototype.filter')}}{{Spec2('ES5.1')}}Initiele definitie. Geimplementeerd in JavaScript 1.6.
{{SpecName('ES6', '#sec-array.prototype.filter', 'Array.prototype.filter')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.prototype.filter', 'Array.prototype.filter')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibiliteit

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
EigenschapChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.8")}}{{CompatIE("9")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
EigenschapAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("1.8")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Zie ook

+ + diff --git a/files/nl/web/javascript/reference/global_objects/array/find/index.html b/files/nl/web/javascript/reference/global_objects/array/find/index.html new file mode 100644 index 0000000000..2d9443ef47 --- /dev/null +++ b/files/nl/web/javascript/reference/global_objects/array/find/index.html @@ -0,0 +1,224 @@ +--- +title: Array.prototype.find() +slug: Web/JavaScript/Reference/Global_Objects/Array/find +tags: + - Array + - ECMAScript 2015 + - ECMAScript6 + - JavaScript + - Method + - Prototype + - polyfill +translation_of: Web/JavaScript/Reference/Global_Objects/Array/find +--- +
{{JSRef}}
+ +

De find()-methode geeft de waarde van het eerste array element dat aan de testfunctie voldoet terug. Als geen van de elementen uit het array aan de testfunctie voldoen, dan wordt {{jsxref("undefined")}} teruggegeven.

+ +

Zie ook de {{jsxref("Array.findIndex", "findIndex()")}}-methode, die de index van het gevonden element in de array teruggeeft in plaats van de waarde zelf.

+ +

Syntaxis

+ +
arr.find(callback[, thisArg])
+ +

Parameters

+ +
+
callback
+
Functie om voor alle waarden in de array uit te voeren, die drie argumenten accepteert: +
+
element
+
Het huidige element uit de array dat wordt verwerkt.
+
index
+
De index van het huidige element uit de array dat wordt verwerkt.
+
array
+
De array waarop find werd aangeroepen.
+
+
+
thisArg
+
Optioneel. Object om voor this te gebruiken tijdens het uitvoeren van callback.
+
+ +

Retourwaarde

+ +

Een waarde in de array als een element aan de testfunctie voldoet, anders {{jsxref("undefined")}}.

+ +

Beschrijving

+ +

De find-methode voert de callback-functie eenmaal per aanwezig element in de array uit, totdat er één wordt gevonden waarvoor callback een waarde true teruggeeft. Als een dergelijk element wordt gevonden, geeft find direct de waarde van dat element terug. In andere gevallen geeft find {{jsxref("undefined")}} terug nadat alle elementen uit de array zijn doorlopen. callback wordt alleen aangeroepen voor indexen van de array waaraan een waarde is toegekend; de functie wordt niet aangeroepen voor indexen die zijn verwijderd of waaraan nooit een waarde is toegekend.

+ +

callback wordt aangeroepen met drie argumenten: de waarde van het element, de index van het element en het Array-object waarover wordt geïtereerd.

+ +

Als een thisArg-parameter aan find wordt meegegeven, wordt deze voor elke aanroep van callback gebruikt als de waarde voor this. Als er geen waarde voor is opgegeven, wordt {{jsxref("undefined")}} gebruikt.

+ +

find wijzigt de array waarop de methode wordt aangeroepen niet.

+ +

Het bereik van de elementen die door find worden verwerkt, wordt ingesteld voor de eerste aanroep van callback. Elementen die aan de array worden toegevoegd nadat de aanroep naar find begint, worden niet door callback bezocht. Als een bestaand, maar nog niet bezocht element van de array door callback wordt gewijzigd, zal de waarde van dit element die aan callback wordt meegegeven de waarde worden die eraan was toegekend op het moment dat find de index van dat element bereikte; verwijderde elementen worden niet bezocht.

+ +

Voorbeelden

+ +

Een object in een array zoeken via een van zijn eigenschappen

+ +
var voorraad = [
+    {naam: 'appels', aantal: 2},
+    {naam: 'bananen', aantal: 0},
+    {naam: 'kersen', aantal: 5}
+];
+
+function zoekKersen(fruit) {
+    return fruit.naam === 'kersen';
+}
+
+console.log(voorraad.find(zoekKersen)); // { naam: 'kersen', aantal: 5 }
+ +

Een priemgetal in een array zoeken

+ +

Het volgende voorbeeld zoekt een element in de array dat een priemgetal is (of geeft {{jsxref("undefined")}} terug als er geen priemgetal is).

+ +
function isPriem(element) {
+  var start = 2;
+  while (start <= Math.sqrt(element)) {
+    if (element % start++ < 1) {
+      return false;
+    }
+  }
+  return element > 1;
+}
+
+console.log([4, 6, 8, 12].find(isPriem)); // niet gedefinieerd, niet gevonden
+console.log([4, 5, 8, 12].find(isPriem)); // 5
+
+ +

Polyfill

+ +

Deze methode is aan de ECMAScript 2015-specificatie toegevoegd en is mogelijk nog niet in alle JavaScript-implementaties beschikbaar. Met de volgende snippet kan Array.prototype.find echter worden ‘gepolyfilled’:

+ +
// https://tc39.github.io/ecma262/#sec-array.prototype.find
+if (!Array.prototype.find) {
+  Object.defineProperty(Array.prototype, 'find', {
+    value: function(predicate) {
+     // 1. Let O be ? ToObject(this value).
+      if (this == null) {
+        throw new TypeError('"this" is null or not defined');
+      }
+
+      var o = Object(this);
+
+      // 2. Let len be ? ToLength(? Get(O, "length")).
+      var len = o.length >>> 0;
+
+      // 3. If IsCallable(predicate) is false, throw a TypeError exception.
+      if (typeof predicate !== 'function') {
+        throw new TypeError('predicate must be a function');
+      }
+
+      // 4. If thisArg was supplied, let T be thisArg; else let T be undefined.
+      var thisArg = arguments[1];
+
+      // 5. Let k be 0.
+      var k = 0;
+
+      // 6. Repeat, while k < len
+      while (k < len) {
+        // a. Let Pk be ! ToString(k).
+        // b. Let kValue be ? Get(O, Pk).
+        // c. Let testResult be ToBoolean(? Call(predicate, T, « kValue, k, O »)).
+        // d. If testResult is true, return kValue.
+        var kValue = o[k];
+        if (predicate.call(thisArg, kValue, k, o)) {
+          return kValue;
+        }
+        // e. Increase k by 1.
+        k++;
+      }
+
+      // 7. Return undefined.
+      return undefined;
+    }
+  });
+}
+ +

Specificaties

+ + + + + + + + + + + + + + + + + + + +
SpecificatieStatusOpmerking
{{SpecName('ES6', '#sec-array.prototype.find', 'Array.prototype.find')}}{{Spec2('ES6')}}Eerste definitie.
{{SpecName('ESDraft', '#sec-array.prototype.find', 'Array.prototype.find')}}{{Spec2('ESDraft')}}
+ +

Browsercompatibiliteit

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FunctieChromeFirefox (Gecko)Internet ExplorerEdgeOperaSafari
Basisondersteuning{{CompatChrome(45.0)}}{{CompatGeckoDesktop("25.0")}}{{CompatNo}}12{{CompatNo}}{{CompatSafari("7.1")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FunctieAndroidChrome voor AndroidFirefox Mobile (Gecko)IE MobileEdgeOpera MobileSafari Mobile
Basisondersteuning{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile("25.0")}}{{CompatNo}}12{{CompatNo}}8.0
+
+ +

Zie ook

+ + diff --git a/files/nl/web/javascript/reference/global_objects/array/findindex/index.html b/files/nl/web/javascript/reference/global_objects/array/findindex/index.html new file mode 100644 index 0000000000..906d5465e2 --- /dev/null +++ b/files/nl/web/javascript/reference/global_objects/array/findindex/index.html @@ -0,0 +1,177 @@ +--- +title: Array.prototype.findIndex() +slug: Web/JavaScript/Reference/Global_Objects/Array/findIndex +tags: + - Méthode +translation_of: Web/JavaScript/Reference/Global_Objects/Array/findIndex +--- +
{{JSRef}}
+ +

De methode findIndex() geeft de index terug van het eerste element in de array waarvoor de gegeven functie voldoet. Indien er geen element wordt gevonden, zal -1 teruggegeven worden.

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

Zie ook de methode {{jsxref("Array.find", "find()")}}, die een waarde teruggeeft van het gevonden element in plaats van de index.

+ +

Syntax

+ +
arr.findIndex(callback[, thisArg])
+ +

Parameters

+ +
+
callback
+
De functie die wordt uitgevoerd voor elk element in de array, met volgende drie argumenten: +
+
element
+
Het huidig te evalueren element uit de array.
+
index{{optional_inline}}
+
De index van het huidig te evalueren element binnen de array.
+
array{{optional_inline}}
+
De array waarop de methode findIndex was aangeroepen.
+
+
+
thisArg{{optional_inline}}
+
Optioneel. Het object dat als this kan gebruikt worden tijdens de uitvoer van callback.
+
+ +

Return value

+ +

De index binnen de array van het gevonden element; anders, -1.

+ +

Beschrijving

+ +

De methode findIndex voert de callback function uit voor elke index uit de array 0..length-1 (inclusief) tot wanneer er een element is waarvoor callback een waarde teruggeeft overeenkomstig met true. Als zo een element wordt gevonden, dan geeft findIndex onmiddellijk de index terug van deze iteratie. Als de functie voor geen enkel element voldoet of als length van de array 0 is, zal findIndex -1 teruggeven.  In tegenstelling tot andere array methodes zoals Array#some, wordt callback ook aangeroepen ook voor indexen zonder element in de array.

+ +

callback heeft drie argumenten: de waarde van het element, de index van het element, en het Array element dat wordt doorlopen.

+ +

Als een thisArg parameter wordt opgegeven voor findIndex zal het gebruikt worden als this bij elke aanroep van callback. Als het niet wordt opgegeven dan wordt {{jsxref("undefined")}} gebruikt.

+ +

findIndex past de array waarop het wordt aangeroepen niet aan.

+ +

De reeks van elementen verwerkt door findIndex wordt opgemaakt voor de eerste aanroep van callback. Elementen die aan de array worden toegevoegd na de aanroep van findIndex zullen niet worden doorlopen door callback. Als een bestaand element, dat nog niet werd doorlopen, aangepast wordt door callback, dan zal deze waarde doorgegeven aan callback; verwijderde elementen worden ook doorlopen.

+ +

Examples

+ +

Vind de index van een priemgetal in een array

+ +

Het volgende voorbeeld toont hoe een priemgetal kan gevonden worden in een array met getallen (of -1 als er geen priemgetal in de array zit).

+ +
function isPrime(element, index, array) {
+  var start = 2;
+  while (start <= Math.sqrt(element)) {
+    if (element % start++ < 1) {
+      return false;
+    }
+  }
+  return element > 1;
+}
+
+console.log([4, 6, 8, 12].findIndex(isPrime)); // -1, not found
+console.log([4, 6, 7, 12].findIndex(isPrime)); // 2
+
+ +

Vind index met een arrow function

+ +

Het volgende voorbeeld toont hoe een element uit de array fruits kan gevonden worden met de arrow function syntax.

+ +
const fruits = ["apple", "banana", "cantaloupe", "blueberries", "grapefruit"];
+
+const index = fruits.findIndex(fruit => fruit === "blueberries");
+
+console.log(index); // 3
+console.log(fruits[index]); // blueberries
+
+ +

Polyfill

+ +
// https://tc39.github.io/ecma262/#sec-array.prototype.findIndex
+if (!Array.prototype.findIndex) {
+  Object.defineProperty(Array.prototype, 'findIndex', {
+    value: function(predicate) {
+     // 1. Let O be ? ToObject(this value).
+      if (this == null) {
+        throw new TypeError('"this" is null or not defined');
+      }
+
+      var o = Object(this);
+
+      // 2. Let len be ? ToLength(? Get(O, "length")).
+      var len = o.length >>> 0;
+
+      // 3. If IsCallable(predicate) is false, throw a TypeError exception.
+      if (typeof predicate !== 'function') {
+        throw new TypeError('predicate must be a function');
+      }
+
+      // 4. If thisArg was supplied, let T be thisArg; else let T be undefined.
+      var thisArg = arguments[1];
+
+      // 5. Let k be 0.
+      var k = 0;
+
+      // 6. Repeat, while k < len
+      while (k < len) {
+        // a. Let Pk be ! ToString(k).
+        // b. Let kValue be ? Get(O, Pk).
+        // c. Let testResult be ToBoolean(? Call(predicate, T, « kValue, k, O »)).
+        // d. If testResult is true, return k.
+        var kValue = o[k];
+        if (predicate.call(thisArg, kValue, k, o)) {
+          return k;
+        }
+        // e. Increase k by 1.
+        k++;
+      }
+
+      // 7. Return -1.
+      return -1;
+    },
+    configurable: true,
+    writable: true
+  });
+}
+
+ +

Als je echt verouderde JavaScript engines moet blijven ondersteunen die Object.defineProperty niet supporteren, is het beter van Array.prototype methodes helemaal niet te voorzien als polyfill, omdat je ze toch niet niet-enumereerbaar kan maken.

+ +

Specificaties

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-array.prototype.findindex', 'Array.prototype.findIndex')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-array.prototype.findIndex', 'Array.prototype.findIndex')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ +
+ + +

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

+
+ +

Zie ook

+ + diff --git a/files/nl/web/javascript/reference/global_objects/array/includes/index.html b/files/nl/web/javascript/reference/global_objects/array/includes/index.html new file mode 100644 index 0000000000..104c9a7705 --- /dev/null +++ b/files/nl/web/javascript/reference/global_objects/array/includes/index.html @@ -0,0 +1,220 @@ +--- +title: Array.prototype.includes() +slug: Web/JavaScript/Reference/Global_Objects/Array/includes +translation_of: Web/JavaScript/Reference/Global_Objects/Array/includes +--- +
{{JSRef}}
+ +

De methode includes() controleert of de opgegeven waarde aanwezig is in een reeks of niet. Als dit waar is geeft het true, anders false.

+ +
var a = [1, 2, 3];
+a.includes(2); // true
+a.includes(4); // false
+ +

Syntax

+ +
arr.includes(zoekWaarde[vanIndex])
+ +

Parameters

+ +
+
zoekWaarde
+
Het element om te zoeken.
+
vanIndex {{optional_inline}}
+
De positie binnen de array waar begonnen wordt met het zoeken naar zoekWaarde. Een negatieve waarde zoekt oplopend uit de index van array.length + vanIndex. Standaard 0.
+
+ +

Antwoord waarde

+ +

Een {{jsxref("Boolean")}}. true als de zoekWaarde is gevonden. false als dit niet het geval is. de 0 (nul) worden als gelijk gezien. -0 is gelijk aan 0 en +0. false staat niet gelijk aan 0

+ +

Voorbeelden

+ +

 

+ +
[1, 2, 3].includes(2);     // true (waar)
+[1, 2, 3].includes(4);     // false (niet waar)
+[1, 2, 3].includes(3, 3);  // false (niet waar)
+[1, 2, 3].includes(3, -1); // true (waar)
+[1, 2, NaN].includes(NaN); // true (waar) (NaN betekent "Not A Number" oftewel "geen nummer" in het Engels)
+
+ +

 

+ +

fromIndex is groter dan of gelijk aan de array lengte

+ +

Als fromIndex groter of gelijk is aan de lengte van de array, wordt er false geantwoord.  De array zal niet doorzocht worden.

+ +
var arr = ['a', 'b', 'c'];
+
+arr.includes('c', 3);   // false (niet waar)
+arr.includes('c', 100); // false (niet waar)
+ +

De berekende index is minder dan 0

+ +

Als vanIndex negatief is, zal de berekende index worden berekend om te worden gebruikt als een positie in de array waarop moet worden gezocht naar zoekElement. Als de berekende index lager is dan 0, wordt de hele array doorzocht.

+ +
// array lengte is 3
+// vanIndex is -100
+// berekende index is 3 + (-100) = -97
+
+var arr = ['a', 'b', 'c'];
+
+arr.includes('a', -100); // true (waar)
+arr.includes('b', -100); // true (waar)
+arr.includes('c', -100); // true (waar)
+ +

includes() gebruiken als een algemene methode

+ +

De includes() methode is natuurlijk algemeen. Het is niet nodig dat deze waarde een Array is. Het onderstaande voorbeeld laat de includes() methode zien in een functie's argumenten lijst. 

+ +
(function() {
+  console.log([].includes.call(arguments, 'a')); // true (waar)
+  console.log([].includes.call(arguments, 'd')); // false (niet waar)
+})('a','b','c');
+ +

Polyfill

+ +
// https://tc39.github.io/ecma262/#sec-array.prototype.includes
+if (!Array.prototype.includes) {
+  Object.defineProperty(Array.prototype, 'includes', {
+    value: function(searchElement, fromIndex) {
+
+      // 1. Let O be ? ToObject(this value).
+      if (this == null) {
+        throw new TypeError('"this" is null or not defined');
+      }
+
+      var o = Object(this);
+
+      // 2. Let len be ? ToLength(? Get(O, "length")).
+      var len = o.length >>> 0;
+
+      // 3. If len is 0, return false.
+      if (len === 0) {
+        return false;
+      }
+
+      // 4. Let n be ? ToInteger(fromIndex).
+      //    (If fromIndex is undefined, this step produces the value 0.)
+      var n = fromIndex | 0;
+
+      // 5. If n ≥ 0, then
+      //  a. Let k be n.
+      // 6. Else n < 0,
+      //  a. Let k be len + n.
+      //  b. If k < 0, let k be 0.
+      var k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
+
+      // 7. Repeat, while k < len
+      while (k < len) {
+        // a. Let elementK be the result of ? Get(O, ! ToString(k)).
+        // b. If SameValueZero(searchElement, elementK) is true, return true.
+        // c. Increase k by 1.
+        // NOTE: === provides the correct "SameValueZero" comparison needed here.
+        if (o[k] === searchElement) {
+          return true;
+        }
+        k++;
+      }
+
+      // 8. Return false
+      return false;
+    }
+  });
+}
+
+ +

If you need to support truly obsolete JavaScript engines that don't support Object.defineProperty, it's best not to polyfill Array.prototype methods at all, as you can't make them non-enumerable.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES7', '#sec-array.prototype.includes', 'Array.prototype.includes')}}{{Spec2('ES7')}}Initial definition.
{{SpecName('ESDraft', '#sec-array.prototype.includes', 'Array.prototype.includes')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerEdgeOperaSafari
Basic support +

{{CompatChrome(47)}}

+
{{CompatGeckoDesktop("43")}}{{CompatNo}}14349
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}} +

{{CompatChrome(47)}}

+
{{CompatGeckoMobile("43")}}{{CompatNo}}349 +

{{CompatChrome(47)}}

+
+
+ +

See also

+ + diff --git a/files/nl/web/javascript/reference/global_objects/array/index.html b/files/nl/web/javascript/reference/global_objects/array/index.html new file mode 100644 index 0000000000..37394ccd2e --- /dev/null +++ b/files/nl/web/javascript/reference/global_objects/array/index.html @@ -0,0 +1,485 @@ +--- +title: Array +slug: Web/JavaScript/Reference/Global_Objects/Array +tags: + - Array + - JavaScript + - NeedsTranslation + - TopicStub +translation_of: Web/JavaScript/Reference/Global_Objects/Array +--- +
{{JSRef}}
+ +

De JavaScript Array klasse is een globaal object dat wordt gebruikt bij de constructie van arrays; een hoog-geplaatst, lijstachtig object.

+ +

Beschrijving

+ +

Arrays zijn lijstachtige objecten waarvan het prototype methoden heeft om te iterereren, muteren en kopiëren. Noch de lengte van een Javascript-array, noch de typen elementen staan vast. Aangezien de lengte van een array op elk moment kan veranderen en gegevens kunnen worden opgeslagen op niet-aangrenzende locaties, is het niet gegarandeerd dat de gegevensplekken in de Javascript-array vast staan. Over het algemeen zijn dit handige kenmerken; maar als deze functies niet wenselijk zijn voor jouw specifieke gebruik, kun je overwegen om Typed Arrays te gebruiken.

+ +

Arrays kunnen geen tekenreeksen gebruiken als elementindexen (zoals in een associatieve array), maar moeten hele getallen gebruiken. Een element instellen of ophalen met behulp van de haakjesnotatie (of puntnotatie) zal geen element uit de array ophalen of instellen. Maar zal proberen om een variabele uit de object property collection van de array op te halen of in te stellen. De objecteigenschappen van de array en de lijst met arrayelementen zijn namelijk gescheiden en de kopie- en mutatiebewerkingen van de array kunnen niet worden toegepast op deze benoemde eigenschappen

+ +

Alledaagse handelingen

+ +

Maak een Array aan

+ +
let fruit = ["Appel", "Banaan"];
+
+console.log(fruit.length);
+// 2
+
+ +

Toegang tot (indexeren van) een Array-item

+ +
let eerste = fruit[0];
+// Appel
+
+let laatste = fruit[fruit.length - 1];
+// Banaan
+
+ +

Itereer over een Array

+ +
fruit.forEach(function (item, index, array) {
+  console.log(item, index);
+});
+// Appel 0
+// Banaan 1
+
+ +

Toevoegen op het eind van de Array

+ +
let nieuweLengte = fruit.push("Sinaasappel");
+// ["Appel", "Banaan", "Sinaasappel"]
+
+ +

Verwijder op het eind van de Array

+ +
let laatste = fruit.pop(); // verwijder de Sinaasappel op het eind
+// ["Appel", "Banaan"];
+
+ +

Verwijder van de eerste plaats van een array

+ +
let eerste = fruit.shift(); // verwijder appel van de eerste plaats
+// ["Banaan"];
+
+ +

Voeg toe aan de eerste plaats van een Array

+ +
let nieuweLengte = fruit.unshift("Aardbei") // voeg de aarbei toe op de eerste plaats
+// ["Aardbei", "Banaan"];
+
+ +

Zoek de index van een item in de Array

+ +
fruit.push("Mango");
+// ["Aardbei", "Banaan", "Mango"]
+
+let positie = fruit.indexOf("Banaan");
+// 1
+
+ +

Verwijder een item van de indexpositie

+ +
let verwijderItem = fruit.splice(positie, 1); // hiermee kan je een item verwijderen
+// ["Aardbei", "Mango"]
+
+ +

Kopieer een array

+ +
let Kopie = fruit.slice(); // hiermee maak je een kopie van de matrix
+// ["Aardbei", "Mango"]
+
+ +

Syntaxis

+ +
[element0, element1, ..., elementN]
+new Array(element0, element1[, ...[, elementN]])
+new Array(arrayLength)
+ +
+
elementN
+
Een JavaScript-array wordt geïnitialiseerd met de gegeven elementen, behalve in het geval dat een enkel argument wordt doorgegeven aan de Array-constructor en dat argument een getal is. (Zie hieronder.) Merk op dat dit speciale geval alleen van toepassing is op JavaScript-arrays die zijn gemaakt met de Array-constructor, niet op array-literals die zijn gemaakt met de haakjesyntaxis.
+
arrayLengte
+
Als het enige argument dat aan de constructor Array is doorgegeven, een geheel getal tussen 0 en 232-1 (inclusief) is, geeft dit een nieuwe JavaScript-array terug waarvan de lengte is ingesteld op dat aantal. Als het argument een ander getal is, wordt er een uitzondering {{jsxref ("RangeError")}} gegenereerd.
+
+
+ +

Toegang tot array-elementen

+ +

JavaScript-arrays zijn geïndexeerd vanaf nul: het eerste element van een array staat op index 0 en het laatste element staat op de index die gelijk is aan de waarde van de eigenschap {{jsxref ("Array.length", "length")}} van de array min 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.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.observe()")}} {{non-standard_inline}}
+
Asynchronously observes changes to Arrays, similar to {{jsxref("Object.observe()")}} for objects. It provides a stream of changes in order of occurrence.
+
{{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 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 ES6 {{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
+
+ +

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/nl/web/javascript/reference/global_objects/array/indexof/index.html b/files/nl/web/javascript/reference/global_objects/array/indexof/index.html new file mode 100644 index 0000000000..19d72e4ec5 --- /dev/null +++ b/files/nl/web/javascript/reference/global_objects/array/indexof/index.html @@ -0,0 +1,244 @@ +--- +title: Array.prototype.indexOf() +slug: Web/JavaScript/Reference/Global_Objects/Array/indexOf +tags: + - Array + - Méthode + - indexof + - zoeken +translation_of: Web/JavaScript/Reference/Global_Objects/Array/indexOf +--- +
{{JSRef}}
+ +

De indexOf() methode retourneert het index getal behorende bij het gegeven element in een array. Indien het element niet is gevonden wordt -1 geretourneerd.

+ +

Syntax

+ +
arr.indexOf(searchElement[, fromIndex = 0])
+ +

Parameters

+ +
+
searchElement
+
Het te doorzoeken element in de Array.
+
fromIndex
+
De index waar vanaf gezocht moet worden. Als de index groter is dan de lengte van de array, dan wordt -1 geretourneerd welke inhoudt dat de array niet doorzocht is. Als de gegeven index een negatief getal is, wordt dit gebruikt als offset van het einde van de array. Opmerking:  Als de gegeven index negatief is, wordt de array nog steeds van voren naar achteren doorzocht. Als de berekende index minder dan 0 is, dan wordt de gehele array doorzocht. Standaard: 0 (gehele array wordt doorzocht).
+
+ +

Return waarde

+ +

De eerste index van het element in de array; -1 als het element niet is gevonden.

+ +

Beschrijving

+ +

indexOf() vergelijkt searchElement met elementen van de Array gebruikmakend van 'strict equality' (dezelfde methode zoals gebruikt door === of de gelijk-aan operator).

+ +

Voorbeelden

+ +

Het gebruik van indexOf()

+ +

De volgende voorbeelden gebruiken indexOf() om waarden in een array te lokalizeren. 

+ +
var array = [2, 9, 9];
+array.indexOf(2);     // 0
+array.indexOf(7);     // -1
+array.indexOf(9, 2);  // 2
+array.indexOf(2, -1); // -1
+array.indexOf(2, -3); // 0
+
+ +

Alle voorvallen vinden van een element

+ +
var indices = [];
+var array = ['a', 'b', 'a', 'c', 'a', 'd'];
+var element = 'a';
+var idx = array.indexOf(element);
+while (idx != -1) {
+  indices.push(idx);
+  idx = array.indexOf(element, idx + 1);
+}
+console.log(indices);
+// [0, 2, 4]
+
+ +

Zoek of een element bestaat in de array of niet en update de array

+ +
function updateVegetablesCollection (veggies, veggie) {
+    if (veggies.indexOf(veggie) === -1) {
+        veggies.push(veggie);
+        console.log('New veggies collection is : ' + veggies);
+    } else if (veggies.indexOf(veggie) > -1) {
+        console.log(veggie + ' already exists in the veggies collection.');
+    }
+}
+
+var veggies = ['potato', 'tomato', 'chillies', 'green-pepper'];
+
+updateVegetablesCollection(veggies, 'spinach');
+// New veggies collection is : potato,tomato,chillies,green-papper,spinach
+updateVegetablesCollection(veggies, 'spinach');
+// spinach already exists in the veggies collection.
+
+ +

Polyfill

+ +

indexOf() werd aan de ECMA-262 standaard toegevoegd in de 5de editie; als zodanig kan het niet in alle browsers voorkomen. U kunt hier een workaround voor gebruiken door de volgende code te plaatsen in het begin van uw scripts. Hiermee kunt u indexOf() gebruiken als er nog geen native support beschikbaar is. Dit algoritme vergelijkt hetgeen gespecificeerd in ECMA-262, 5de editie, aangenomen dat  {{jsxref("Global_Objects/TypeError", "TypeError")}} en {{jsxref("Math.abs()")}} hun eigen waarden hebben.

+ +
// Production steps of ECMA-262, Edition 5, 15.4.4.14
+// Referentie: http://es5.github.io/#x15.4.4.14
+if (!Array.prototype.indexOf) {
+  Array.prototype.indexOf = function(searchElement, fromIndex) {
+
+    var k;
+
+    // 1. Let o be the result of calling ToObject passing
+    //    the this value as the argument.
+    if (this == null) {
+      throw new TypeError('"this" is null or not defined');
+    }
+
+    var o = Object(this);
+
+    // 2. Let lenValue be the result of calling the Get
+    //    internal method of o with the argument "length".
+    // 3. Let len be ToUint32(lenValue).
+    var len = o.length >>> 0;
+
+    // 4. If len is 0, return -1.
+    if (len === 0) {
+      return -1;
+    }
+
+    // 5. If argument fromIndex was passed let n be
+    //    ToInteger(fromIndex); else let n be 0.
+    var n = +fromIndex || 0;
+
+    if (Math.abs(n) === Infinity) {
+      n = 0;
+    }
+
+    // 6. If n >= len, return -1.
+    if (n >= len) {
+      return -1;
+    }
+
+    // 7. Als n >= 0, dan Let k be n.
+    // 8. Anders, n<0, Let k be len - abs(n).
+    //    Als k kleiner is dan 0, dan let k be 0.
+    k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
+
+    // 9. Herhaal, zolang k < len
+    while (k < len) {
+      // a. Let Pk be ToString(k).
+      //   Dit is impliciet voor de linkerkant van de vergelijking
+      // b. Let kPresent be the result of calling the
+      //    HasProperty internal method of o with argument Pk.
+      //   This step can be combined with c
+      // c. If kPresent is true, then
+      //    i.  Let elementK be the result of calling the Get
+      //        internal method of o with the argument ToString(k).
+      //   ii.  Let same be the result of applying the
+      //        Strict Equality Comparison Algorithm to
+      //        searchElement and elementK.
+      //  iii.  If same is true, return k.
+      if (k in o && o[k] === searchElement) {
+        return k;
+      }
+      k++;
+    }
+    return -1;
+  };
+}
+
+ +

Specificaties

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificatieStatusOpmerking
{{SpecName('ES5.1', '#sec-15.4.4.14', 'Array.prototype.indexOf')}}{{Spec2('ES5.1')}}Oorspronkelijke definitie. Geïmplementeerd in JavaScript 1.6.
{{SpecName('ES6', '#sec-array.prototype.indexof', 'Array.prototype.indexOf')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.prototype.indexof', 'Array.prototype.indexOf')}}{{Spec2('ESDraft')}} 
+ +

Browsercompatibiliteit

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
KenmerkChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basis Ondersteuning{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.8")}}{{CompatIE("9")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
KenmerkAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basis Ondersteuning{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("1.8")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Compatibiliteit opmerkingen

+ + + +

Bekijk ook

+ + diff --git a/files/nl/web/javascript/reference/global_objects/array/isarray/index.html b/files/nl/web/javascript/reference/global_objects/array/isarray/index.html new file mode 100644 index 0000000000..19566a4ced --- /dev/null +++ b/files/nl/web/javascript/reference/global_objects/array/isarray/index.html @@ -0,0 +1,142 @@ +--- +title: Array.isArray() +slug: Web/JavaScript/Reference/Global_Objects/Array/isArray +translation_of: Web/JavaScript/Reference/Global_Objects/Array/isArray +--- +
{{JSRef}}
+ +

De Array.isArray() bepaalt of de gegeven waarde een {{jsxref("Array")}} is. 

+ +

Syntax

+ +
Array.isArray(obj)
+ +

Parameters

+ +
+
obj
+
Het te onderzoeken object.
+
+ +

Beschrijving

+ +

Indien het object een {{jsxref("Array")}} is, dan is true het resultaat, anders wordt dit false

+ +

Bekijk het artikel “Determining with absolute accuracy whether or not a JavaScript object is an array” voor nadere details.

+ +

Voorbeelden

+ +
// alle van de volgende call resulteren in true
+Array.isArray([]);
+Array.isArray([1]);
+Array.isArray(new Array());
+// Weinig bekend: Array.prototype is zelf een array:
+Array.isArray(Array.prototype);
+
+// alle van de volgende calls resulteren in false
+Array.isArray();
+Array.isArray({});
+Array.isArray(null);
+Array.isArray(undefined);
+Array.isArray(17);
+Array.isArray('Array');
+Array.isArray(true);
+Array.isArray(false);
+Array.isArray({ __proto__: Array.prototype });
+
+ +

Polyfill

+ +

De volgende code zal de methode Array.isArray() aanmaken indien deze niet van huis uit werd meegegeven:

+ +
if (!Array.isArray) {
+  Array.isArray = function(arg) {
+    return Object.prototype.toString.call(arg) === '[object Array]';
+  };
+}
+
+ +

Specificaties

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificatiesStatusCommentaar
{{SpecName('ES5.1', '#sec-15.4.3.2', 'Array.isArray')}}{{Spec2('ES5.1')}}Initiele definitie. Geimplementeerd in JavaScript 1.8.5.
{{SpecName('ES6', '#sec-array.isarray', 'Array.isArray')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.isarray', 'Array.isArray')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibiliteit

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
EigenschapChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("5")}}{{CompatGeckoDesktop("2.0")}}{{CompatIE("9")}}{{CompatOpera("10.5")}}{{CompatSafari("5")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
EigenschapAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("2.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Zie ook

+ + diff --git a/files/nl/web/javascript/reference/global_objects/array/map/index.html b/files/nl/web/javascript/reference/global_objects/array/map/index.html new file mode 100644 index 0000000000..8ac69797ad --- /dev/null +++ b/files/nl/web/javascript/reference/global_objects/array/map/index.html @@ -0,0 +1,324 @@ +--- +title: Array.prototype.map() +slug: Web/JavaScript/Reference/Global_Objects/Array/map +tags: + - ECMAScript6 + - JavaScript + - Méthode + - Prototype + - Referentie + - polyfill + - reeks +translation_of: Web/JavaScript/Reference/Global_Objects/Array/map +--- +
{{JSRef}}
+ +

De map() methode maakt een nieuwe array aan met als inhoud het resultaat van het aanroepen van de meegegeven functie op elk van de elementen uit de originele array.

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

Syntax

+ +
var new_array = arr.map(function callback(currentValue[, index[, array]]) {
+    // Return element for new_array
+}[, thisArg])
+ +

Parameters

+ +
+
callback
+
Functie die een element voor de nieuwe Array produceert en de volgende argumenten aanvaardt: +
+
+
currentValue
+
Het huidige te verwerken element uit de array.
+
index{{optional_inline}}
+
De index van het huidige te verwerken element in die array.
+
array{{optional_inline}}
+
De array waarop map werd opgeroepen.
+
+
+
thisArg{{optional_inline}}
+
Waarde die moet gebruikt worden voor this bij het uitvoeren van callback.
+
+ +

Return value

+ +

Een nieuwe array waarbij elk element het resultaat is van het oproepen van de functie op het overeenkomstige element uit de originele array.

+ +

Beschrijving

+ +

map roept de meegegeven callback functie één keer op voor elk element in een array, in volgorde, en maakt een nieuwe array met de resultaten. callback wordt enkel opgeroepen voor indices van de array die een waarde hebben, inclusief undefined. Het wordt niet opgeroepen voor element die niet (meer) in de array zitten (indices die nog nooit gezet zijn, die werden verwijderd of die nog nooit een waarde hebben gekregen).

+ +

Aangezien map een nieuwe array aanmaakt, heeft het geen zin deze methode aan te roepen als je de geretourneerde array niet gebruikt; gebruik dan eerder forEach of for-of. Gebruik map niet als: A) je de geretourneerde array niet gebruikt, en/of B) de callback functie geen waarde retourneert.

+ +

callback wordt aangeroepen met drie argumenten: de waarde van het element, de index van het element en het Array object zelf dat wordt doorlopen.

+ +

Als een thisArg parameter wordt meegegeven aan map, zal het gebruikt worden als this waarde voor de callback functie. Indien niet, wordt {{jsxref("undefined")}} gebruikt als zijn this waarde. De this waarde zoals callback ze uiteindelijk waarneemt, wordt bepaald volgens de gewone regels voor het bepalen van this zoals waargenomen door een functie.

+ +

map wijzigt de array waarop het wordt aangeroepen niet (ofschoon callback, indien aangeroepen, dat wél kan doen).

+ +

Het aantal elementen dat wordt verwerkt door map wordt bepaald vooraleer de eerste aanroep van callback plaatsvindt. Elementen die worden toegevoegd aan de array nadat de aanroep van map is gebeurd zullen door callback niet worden behandeld. Als bestaande elementen van de array worden gewijzigd, dan zijn de waarden die worden doorgegeven aan callback de waarden op het moment dat map ze beschouwt. Elementen die worden verwijderd na het aanroepen van map en vóór ze werden beschouwd worden niet verwerkt.
+
+ Voor de indices waarop de originele array lege plaatsen bevat, zal ook de resulterende array lege plaatsen bevatten.

+ +

Voorbeelden

+ +

Een array van getallen mappen op een array van vierkantswortels

+ +

De volgende code neemt een array van getallen en creëert een nieuwe array die de vierkantswortels van die getallen bevat.

+ +
var getallen = [1, 4, 9];
+var vierkantsWortels = getallen.map(function(getal) {
+return Math.sqrt(getal)
+});
+// vierkantsWortels is nu [1, 2, 3]
+// getallen is nog steeds [1, 4, 9]
+
+ +

Gebruik van map om objecten te herformateren in een array

+ +

De volgende code neemt een array van objecten en creëert een nieuwe array die de geherformatteerde objecten bevat.

+ +
var kvArray = [{key: 1, value: 10},
+               {key: 2, value: 20},
+               {key: 3, value: 30}];
+
+var reformattedArray = kvArray.map(obj =>{
+   var rObj = {};
+   rObj[obj.key] = obj.value;
+   return rObj;
+});
+// reformattedArray is now [{1: 10}, {2: 20}, {3: 30}],
+
+// kvArray is still:
+// [{key: 1, value: 10},
+//  {key: 2, value: 20},
+//  {key: 3, value: 30}]
+
+ +

Mapping an array of numbers using a function containing an argument

+ +

The following code shows how map works when a function requiring one argument is used with it. The argument will automatically be assigned from each element of the array as map loops through the original array.

+ +
var numbers = [1, 4, 9];
+var doubles = numbers.map(function(num) {
+  return num * 2;
+});
+
+// doubles is now [2, 8, 18]
+// numbers is still [1, 4, 9]
+
+ +

Using map generically

+ +

This example shows how to use map on a {{jsxref("String")}} to get an array of bytes in the ASCII encoding representing the character values:

+ +
var map = Array.prototype.map;
+var a = map.call('Hello World', function(x) {
+  return x.charCodeAt(0);
+});
+// a now equals [72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100]
+
+ +

Using map generically querySelectorAll

+ +

This example shows how to iterate through a collection of objects collected by querySelectorAll. This is because querySelectorAll returns a NodeList which is a collection of objects.
+ In this case we return all the selected options' values on the screen:

+ +
var elems = document.querySelectorAll('select option:checked');
+var values = Array.prototype.map.call(elems, function(obj) {
+  return obj.value;
+});
+
+ +

Easier way would be using {{jsxref("Array.from()")}} method.

+ +

Tricky use case

+ +

(inspired by this blog post)

+ +

It is common to use the callback with one argument (the element being traversed). Certain functions are also commonly used with one argument, even though they take additional optional arguments. These habits may lead to confusing behaviors.

+ +
// Consider:
+['1', '2', '3'].map(parseInt);
+// While one could expect [1, 2, 3]
+// The actual result is [1, NaN, NaN]
+
+// parseInt is often used with one argument, but takes two.
+// The first is an expression and the second is the radix.
+// To the callback function, Array.prototype.map passes 3 arguments:
+// the element, the index, the array
+// The third argument is ignored by parseInt, but not the second one,
+// hence the possible confusion. See the blog post for more details
+// If the link doesn't work
+// here is concise example of the iteration steps:
+// parseInt(string, radix) -> map(parseInt(value, index))
+// first iteration (index is 0): parseInt('1', 0) // results in parseInt('1', 0) -> 1
+// second iteration (index is 1): parseInt('2', 1) // results in parseInt('2', 1) -> NaN
+// third iteration (index is 2): parseInt('3', 2) // results in parseInt('3', 2) -> NaN
+
+function returnInt(element) {
+  return parseInt(element, 10);
+}
+
+['1', '2', '3'].map(returnInt); // [1, 2, 3]
+// Actual result is an array of numbers (as expected)
+
+// Same as above, but using the concise arrow function syntax
+['1', '2', '3'].map( str => parseInt(str) );
+
+// A simpler way to achieve the above, while avoiding the "gotcha":
+['1', '2', '3'].map(Number); // [1, 2, 3]
+// but unlike `parseInt` will also return a float or (resolved) exponential notation:
+['1.1', '2.2e2', '3e300'].map(Number); // [1.1, 220, 3e+300]
+
+ +

One alternative output of the map method being called with parseInt as a parameter runs as follows:

+ +
var xs = ['10', '10', '10'];
+
+xs = xs.map(parseInt);
+
+console.log(xs);
+// Actual result of 10,NaN,2 may be unexpected based on the above description.
+ +

Polyfill

+ +

map was added to the ECMA-262 standard in the 5th edition; as such it may not be present in all implementations of the standard. You can work around this by inserting the following code at the beginning of your scripts, allowing use of map in implementations which do not natively support it. This algorithm is exactly the one specified in ECMA-262, 5th edition, assuming {{jsxref("Object")}}, {{jsxref("TypeError")}}, and {{jsxref("Array")}} have their original values and that callback.call evaluates to the original value of {{jsxref("Function.prototype.call")}}.

+ +
// Production steps of ECMA-262, Edition 5, 15.4.4.19
+// Reference: http://es5.github.io/#x15.4.4.19
+if (!Array.prototype.map) {
+
+  Array.prototype.map = function(callback/*, thisArg*/) {
+
+    var T, A, k;
+
+    if (this == null) {
+      throw new TypeError('this is null or not defined');
+    }
+
+    // 1. Let O be the result of calling ToObject passing the |this|
+    //    value as the argument.
+    var O = Object(this);
+
+    // 2. Let lenValue be the result of calling the Get internal
+    //    method of O with the argument "length".
+    // 3. Let len be ToUint32(lenValue).
+    var len = O.length >>> 0;
+
+    // 4. If IsCallable(callback) is false, throw a TypeError exception.
+    // See: http://es5.github.com/#x9.11
+    if (typeof callback !== 'function') {
+      throw new TypeError(callback + ' is not a function');
+    }
+
+    // 5. If thisArg was supplied, let T be thisArg; else let T be undefined.
+    if (arguments.length > 1) {
+      T = arguments[1];
+    }
+
+    // 6. Let A be a new array created as if by the expression new Array(len)
+    //    where Array is the standard built-in constructor with that name and
+    //    len is the value of len.
+    A = new Array(len);
+
+    // 7. Let k be 0
+    k = 0;
+
+    // 8. Repeat, while k < len
+    while (k < len) {
+
+      var kValue, mappedValue;
+
+      // a. Let Pk be ToString(k).
+      //   This is implicit for LHS operands of the in operator
+      // b. Let kPresent be the result of calling the HasProperty internal
+      //    method of O with argument Pk.
+      //   This step can be combined with c
+      // c. If kPresent is true, then
+      if (k in O) {
+
+        // i. Let kValue be the result of calling the Get internal
+        //    method of O with argument Pk.
+        kValue = O[k];
+
+        // ii. Let mappedValue be the result of calling the Call internal
+        //     method of callback with T as the this value and argument
+        //     list containing kValue, k, and O.
+        mappedValue = callback.call(T, kValue, k, O);
+
+        // iii. Call the DefineOwnProperty internal method of A with arguments
+        // Pk, Property Descriptor
+        // { Value: mappedValue,
+        //   Writable: true,
+        //   Enumerable: true,
+        //   Configurable: true },
+        // and false.
+
+        // In browsers that support Object.defineProperty, use the following:
+        // Object.defineProperty(A, k, {
+        //   value: mappedValue,
+        //   writable: true,
+        //   enumerable: true,
+        //   configurable: true
+        // });
+
+        // For best browser support, use the following:
+        A[k] = mappedValue;
+      }
+      // d. Increase k by 1.
+      k++;
+    }
+
+    // 9. return A
+    return A;
+  };
+}
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES5.1', '#sec-15.4.4.19', 'Array.prototype.map')}}{{Spec2('ES5.1')}}Initial definition. Implemented in JavaScript 1.6.
{{SpecName('ES6', '#sec-array.prototype.map', 'Array.prototype.map')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-array.prototype.map', 'Array.prototype.map')}}{{Spec2('ESDraft')}}
+ +

Browser compatibility

+ +
+ + +

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

+
+ +

See also

+ + diff --git a/files/nl/web/javascript/reference/global_objects/array/push/index.html b/files/nl/web/javascript/reference/global_objects/array/push/index.html new file mode 100644 index 0000000000..db5fe6e5b2 --- /dev/null +++ b/files/nl/web/javascript/reference/global_objects/array/push/index.html @@ -0,0 +1,179 @@ +--- +title: Array.prototype.push() +slug: Web/JavaScript/Reference/Global_Objects/Array/push +tags: + - Array + - JavaScript + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Array/push +--- +
{{JSRef}}
+ +

De push() methode voegt een of meerdere elementen toe aan het einde van een array en geeft de nieuwe lengte van de array terug.

+ +

Syntaxis

+ +
arr.push(element1, ..., elementN)
+ +

Parameters

+ +
+
elementN
+
De elementen om toe te voegen aan het einde van de array.
+
+ +

Geeft terug

+ +

De nieuwe {{jsxref("Array.length", "length")}} eigenschap van het object waarop deze methode is aangeroepen.

+ +

Beschrijving

+ +

De push methode voegt waardes toe aan een array.

+ +

push is opzettelijk generiek. Deze methode kan gebruikt worden met {{jsxref("Function.call", "call()")}} of {{jsxref("Function.apply", "apply()")}} op objecten welke op arrays lijken. De push methode rekent op een length eigenschap om te kunnen weten waar de nieuwe waardes toegevoegd moeten worden. Als de length eigenschap niet kan worden omgezet naar een getal, wordt de gebruikte index 0. Dit geldt ook wanneer length niet bestaat, in welk geval length gemaakt wordt, ook met waarde 0.

+ +

De enige native, array-achtige objecten zijn {{jsxref("Global_Objects/String", "strings", "", 1)}}, hoewel zij niet geschikt zijn voor het gebruik van deze methode, omdat strings onveranderlijk zijn.

+ +

Voorbeelden

+ +

Elementen aan een array toevoegen

+ +

De volgende code maakt de sports array met twee elementen en voegt twee elementen er aan toe. De total variabele bevat de nieuwe lengte van de array.

+ +
var sports = ['soccer', 'baseball'];
+var total = sports.push('football', 'swimming');
+
+console.log(sports); // ['soccer', 'baseball', 'football', 'swimming']
+console.log(total);  // 4
+
+ +

Twee arrays samenvoegen

+ +

Dit voorbeeld gebruikt {{jsxref("Function.apply", "apply()")}} om alle elementen van een tweede array te pushen.

+ +
var vegetables = ['parsnip', 'potato'];
+var moreVegs = ['celery', 'beetroot'];
+
+// De tweede array in de eerste voegen
+// Gelijk aan vegetables.push('celery', 'beetroot');
+Array.prototype.push.apply(vegetables, moreVegs);
+
+console.log(vegetables); // ['parsnip', 'potato', 'celery', 'beetroot']
+
+ +

Een object gebruiken op een array-achtige manier

+ +

Zoals hierboven gezegd is push opzettelijk generiek, wat we in ons voordeel kunnen gebruiken. Array.prototype.push werkt ook op objecten, zoals dit voorbeeld laat zien. We maken geen array om een verzameling objecten op te slaan. We slaan de verzameling op in het object zelf en gebruiken call op Array.prototype.push om de methode te laten denken dat we te maken hebben met een array en het werkt. Dit is te danken aan de manier waarop JavaScript toestaat om de context van uitvoer te bepalen.

+ +
var obj = {
+    length: 0,
+
+    addElem: function addElem (elem) {
+        // obj.length wordt automatisch verhoogd elke keer dat een element wordt toegevoegd.
+        [].push.call(this, elem);
+    }
+};
+
+// Lege objecten toevoegen om het idee te laten zien
+obj.addElem({});
+obj.addElem({});
+console.log(obj.length);
+// → 2
+
+ +

Hoewel obj geen array is zorgt de push methode er voor dat obj's length eigenschap wordt verhoogd, zoals ook zou gebeuren als dit gedaan zou worden op een echte array.

+ +

Specificaties

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificatieStatusOpmerking
{{SpecName('ES3')}}{{Spec2('ES3')}}Eerste definitie. Geïmplementeerd in JavaScript 1.2.
{{SpecName('ES5.1', '#sec-15.4.4.7', 'Array.prototype.push')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-array.prototype.push', 'Array.prototype.push')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.prototype.push', 'Array.prototype.push')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibiliteit

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("1.0")}}{{CompatGeckoDesktop("1.7")}}{{CompatIE("5.5")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Zie ook

+ + diff --git a/files/nl/web/javascript/reference/global_objects/array/shift/index.html b/files/nl/web/javascript/reference/global_objects/array/shift/index.html new file mode 100644 index 0000000000..7187acb853 --- /dev/null +++ b/files/nl/web/javascript/reference/global_objects/array/shift/index.html @@ -0,0 +1,110 @@ +--- +title: Array.prototype.shift() +slug: Web/JavaScript/Reference/Global_Objects/Array/shift +translation_of: Web/JavaScript/Reference/Global_Objects/Array/shift +--- +
{{JSRef}}
+ +

De shift() methode verwijdert het eerste element van de array en geeft het element terug als resultaat. Deze methode wijzigt de lengte van de array.

+ +
var a = [1, 2, 3];
+var b = a.shift();
+
+console.log(a); // [2, 3]
+console.log(b); // 1
+
+ +

Syntax

+ +
arr.shift()
+ +

Return value

+ +

Het verwijderde element van de array; {{jsxref("undefined")}} als de array leeg is.

+ +

Description

+ +

De shift methode verwijdert het element met index nul en schuift de volgende waarden met hogere index,  1 positie terug.  Het verwijderde element is het resultaat. Als de {{jsxref("Array.length", "length")}} property 0 is, is het resultaat {{jsxref("undefined")}} .

+ +

shift is bewust generiek; deze methode kan worden {{jsxref("Function.call", "aangeroepen", "", 1)}} of {{jsxref("Function.apply", "toegepast", "", 1)}} op op array gelijkende objecten. Objects zonder length property, die de laatste van een serie van opeenvolgende, op nul gebaseerde numerische properties reflecteren, kunnen zich op een niet betekenisvolle manier gedragen.

+ +

Examples

+ +

Removing an element from an array

+ +

De volgend code toont de myFish array voor en na het verwijderen van het eerste element. Het toont ook het verwijderde element:

+ +
var myFish = ['angel', 'clown', 'mandarin', 'surgeon'];
+
+console.log('myFish before:', JSON.stringify(myFish));
+// myFish before: ['angel', 'clown', 'mandarin', 'surgeon']
+
+var shifted = myFish.shift();
+
+console.log('myFish after:', myFish);
+// myFish after: ['clown', 'mandarin', 'surgeon']
+
+console.log('Removed this element:', shifted);
+// Removed this element: angel
+
+ +

Using shift() method in while loop

+ +

De shift() methode wordt vaak gebruikt als een conditie in een while lus. In het volgende voorbeeld verwijdert elke iteratie het volgende element van de array totdat ze leeg is:

+ +
var names = ["Andrew", "Edward", "Paul", "Chris" ,"John"];
+
+while( (i = names.shift()) !== undefined ) {
+    console.log(i);
+}
+// Andrew, Edward, Paul, Chris, John
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.2.
{{SpecName('ES5.1', '#sec-15.4.4.9', 'Array.prototype.shift')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-array.prototype.shift', 'Array.prototype.shift')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.prototype.shift', 'Array.prototype.shift')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ +
+ + +

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

+
+ +

See also

+ + diff --git a/files/nl/web/javascript/reference/global_objects/array/slice/index.html b/files/nl/web/javascript/reference/global_objects/array/slice/index.html new file mode 100644 index 0000000000..d3dcaf0acb --- /dev/null +++ b/files/nl/web/javascript/reference/global_objects/array/slice/index.html @@ -0,0 +1,269 @@ +--- +title: Array.prototype.slice() +slug: Web/JavaScript/Reference/Global_Objects/Array/slice +translation_of: Web/JavaScript/Reference/Global_Objects/Array/slice +--- +

{{JSRef}}
+ De slice() method geeft een oppervlakkige kopie van een gedeelte van een array terug in een nieuwe array.

+ +

Syntax

+ +
arr.slice([begin[, end]])
+ +

Parameters

+ +
+
begin
+
Bij nul beginnende index (zero-based), van waaruit de extractie begint.
+
Bij een negatieve index, geeft begin het aantal plaatsen (offset) tot aan het einde van de reeks. slice(-2) extraheert de laatste twee elementen van de sequentie.
+
Indien begin niet gedefinieerd is, of gelijkwaardig is aan undefined, dan begint slice bij index 0.
+
end
+
Bij nul beginnende index waarop de extractie gestopt wordt. slice extraheert tot aan, maar exclusief end.
+
slice(1,4) extraheert het tweede element tot het vierde element (elementen met index 1, 2, en 3).
+
Als negatieve index, geeft end een afstand (offset) aan tot het einde van de reeks. slice(2,-1) extraheert het derde element tot het op twee na laatse element in de sequentie.
+
Indien end wordt weggelaten, dan zal slice tot het einde van de reeks toe extraheren (arr.length).
+
+ +

Beschrijving

+ +

slice verandert niet. Het retourneert een oppervlakkige kopie van elementen, ten opzichte van de oorspronkelijke array. Elementen van het origineel, worden als volgt gekopieerd en geretourneerd:

+ + + +

Indien een nieuw element aan de ene array wordt toegevoegd, dan blijft de andere array onaangeroerd.

+ +

Voorbeelden

+ +

Geeft een gedeelte van een bestaande array

+ +
var fruits = ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango'];
+var citrus = fruits.slice(1, 3);
+
+// fruits contains ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango']
+// citrus contains ['Orange','Lemon']
+
+ +

Gebruik slice

+ +

In het volgende voorbeeld, maakt slice een nieuwe array aan, newCar, uit myCar. Beide hebben een referentie aan het object myHonda. Wanneer de kleur van myHonda wordt gewijzigd, dan hebben beide arrays deze wisseling ondergaan.

+ +
// Using slice, create newCar from myCar.
+var myHonda = { color: 'red', wheels: 4, engine: { cylinders: 4, size: 2.2 } };
+var myCar = [myHonda, 2, 'cherry condition', 'purchased 1997'];
+var newCar = myCar.slice(0, 2);
+
+// Display the values of myCar, newCar, and the color of myHonda
+//  referenced from both arrays.
+console.log('myCar = ' + myCar.toSource());
+console.log('newCar = ' + newCar.toSource());
+console.log('myCar[0].color = ' + myCar[0].color);
+console.log('newCar[0].color = ' + newCar[0].color);
+
+// Change the color of myHonda.
+myHonda.color = 'purple';
+console.log('The new color of my Honda is ' + myHonda.color);
+
+// Display the color of myHonda referenced from both arrays.
+console.log('myCar[0].color = ' + myCar[0].color);
+console.log('newCar[0].color = ' + newCar[0].color);
+
+ +

Het script verwerkt dit als volgt:

+ +
myCar = [{color:'red', wheels:4, engine:{cylinders:4, size:2.2}}, 2,
+         'cherry condition', 'purchased 1997']
+newCar = [{color:'red', wheels:4, engine:{cylinders:4, size:2.2}}, 2]
+myCar[0].color = red
+newCar[0].color = red
+The new color of my Honda is purple
+myCar[0].color = purple
+newCar[0].color = purple
+
+ +

Array-achtige objecten

+ +

De slice method kan ook gebruikt worden om Array-like objects / collections om te zetten in een nieuwe Array. Je hoeft dan alleen de methode op zich aan het object te binden. De {{jsxref("Functions/arguments", "arguments")}} binnen een functie is een voorbeeld van een 'array-like object'.

+ +
function list() {
+  return Array.prototype.slice.call(arguments);
+}
+
+var list1 = list(1, 2, 3); // [1, 2, 3]
+
+ +

Binding kan worden verkregen met de  .call functie of {{jsxref("Function.prototype")}} en dit kan ook via reductie door gebruik te maken van [].slice.call(arguments) in plaats van de  Array.prototype.slice.call. Hoe dan ook, het kan worden vereenvoudigd met  {{jsxref("Function.prototype.bind", "bind")}}.

+ +
var unboundSlice = Array.prototype.slice;
+var slice = Function.prototype.call.bind(unboundSlice);
+
+function list() {
+  return slice(arguments);
+}
+
+var list1 = list(1, 2, 3); // [1, 2, 3]
+
+ +

Cross-browser gedrag in de hand werken

+ +

Host objecten zoals DOM-objecten, zijn volgens de spec niet verplicht zich te gedragen zoals in een Mozilla browser, wanneer een omzetting plaatsvindt volgens de Array.prototype.slice methode. IE browsers voor versie 9 doen dit bijvoorbeeld niet. De huidige browser versies van IE, Mozilla, Chrome, Safari en Opera ondersteunen het eerder beschreven oppervlakkige kopie ('shallow copy') gedrag en het is daarmee de-facto het standaard gedrag.
+ Door onderstaande code vooraf te laten gaan aan de eigen code, kun je het toch mogelijk maken dat een browser zich zoals je zou verwachten gaat gedragen en er verder geen afwijkende browser specifieke code gebruikt hoeft te worden.

+ +
/**
+ * Shim for "fixing" IE's lack of support (IE < 9) for applying slice
+ * on host objects like NamedNodeMap, NodeList, and HTMLCollection
+ * (technically, since host objects have been implementation-dependent,
+ * at least before ES6, IE hasn't needed to work this way).
+ * Also works on strings, fixes IE < 9 to allow an explicit undefined
+ * for the 2nd argument (as in Firefox), and prevents errors when
+ * called on other DOM objects.
+ */
+(function () {
+  'use strict';
+  var _slice = Array.prototype.slice;
+
+  try {
+    // Can't be used with DOM elements in IE < 9
+    _slice.call(document.documentElement);
+  } catch (e) { // Fails in IE < 9
+    // This will work for genuine arrays, array-like objects,
+    // NamedNodeMap (attributes, entities, notations),
+    // NodeList (e.g., getElementsByTagName), HTMLCollection (e.g., childNodes),
+    // and will not fail on other DOM objects (as do DOM elements in IE < 9)
+    Array.prototype.slice = function(begin, end) {
+      // IE < 9 gets unhappy with an undefined end argument
+      end = (typeof end !== 'undefined') ? end : this.length;
+
+      // For native Array objects, we use the native slice function
+      if (Object.prototype.toString.call(this) === '[object Array]'){
+        return _slice.call(this, begin, end);
+      }
+
+      // For array like object we handle it ourselves.
+      var i, cloned = [],
+        size, len = this.length;
+
+      // Handle negative value for "begin"
+      var start = begin || 0;
+      start = (start >= 0) ? start : Math.max(0, len + start);
+
+      // Handle negative value for "end"
+      var upTo = (typeof end == 'number') ? Math.min(end, len) : len;
+      if (end < 0) {
+        upTo = len + end;
+      }
+
+      // Actual expected size of the slice
+      size = upTo - start;
+
+      if (size > 0) {
+        cloned = new Array(size);
+        if (this.charAt) {
+          for (i = 0; i < size; i++) {
+            cloned[i] = this.charAt(start + i);
+          }
+        } else {
+          for (i = 0; i < size; i++) {
+            cloned[i] = this[start + i];
+          }
+        }
+      }
+
+      return cloned;
+    };
+  }
+}());
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.2.
{{SpecName('ES5.1', '#sec-15.4.4.10', 'Array.prototype.slice')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-array.prototype.slice', 'Array.prototype.slice')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-array.prototype.slice', 'Array.prototype.slice')}}{{Spec2('ESDraft')}}
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("1.0")}}{{CompatGeckoDesktop("1.7")}}{{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/nl/web/javascript/reference/global_objects/array/splice/index.html b/files/nl/web/javascript/reference/global_objects/array/splice/index.html new file mode 100644 index 0000000000..c373091346 --- /dev/null +++ b/files/nl/web/javascript/reference/global_objects/array/splice/index.html @@ -0,0 +1,177 @@ +--- +title: Array.prototype.splice() +slug: Web/JavaScript/Reference/Global_Objects/Array/splice +translation_of: Web/JavaScript/Reference/Global_Objects/Array/splice +--- +
{{JSRef}}
+ +

De splice()-methode past de inhoud van een array aan door bestaande elementen te verwijderen en/of nieuwe elementen toe te voegen.

+ +

Syntax

+ +
array.splice(start[, deleteCount[, item1[, item2[, ...]]]])
+
+ +

Parameters

+ +
+
start
+
Positie vanwaar de array dient te worden veranderd (met eerste element op 0). Indien groter dan de lengte van de array zal de start worden omgezet naar de lengte van de array. Indien negatief begint hij het absolute aantal vanaf het einde van de array.
+
deleteCount
+
Een getal dat aanduidt hoeveel elementen moeten worden verwijderd. Indien 0 worden er geen elementen verwijderd. In dit geval moet minstens één toe te voegen element worden meegeven. Als de deleteCount groter is dan het overige aantal elementen in de array (beginnend bij de startwaarde) worden al deze overige elementen verwijderd.
+
Indien de deleteCount niet wordt meegegeven, wordt deze als volgt berekend: (arr.length - start). Dit heeft als resultaat dat alle elementen na de startwaarde worden verwijderd.
+
item1, item2, ...
+
De elementen die in de array moeten worden toegevoegd, beginnend op de positie van de start -waarde. Indien niet meegegeven zullen er enkel elementen uit de array verwijderd worden.
+
+ +

Retourwaarde

+ +

Een array die de verwijderde items bevat. Wanneer slechts één element is verwijderd, wordt er een array teruggegeven met één element. Wanneer er geen elementen zijn verwijderd, wordt een lege array teruggegeven.

+ +

Omschrijving

+ +

Wanneer een ander aantal elementen wordt ingevoegd dan het aantal elementen dat wordt verwijderd, zal de array een andere lengte hebben na afloop van de aanroep.

+ +

Voorbeelden

+ +

Gebruik van splice()

+ +

The following script illustrates the use of splice():

+ +
var myFish = ['angel', 'clown', 'mandarin', 'surgeon'];
+
+// removes 0 elements from index 2, and inserts 'drum'
+var removed = myFish.splice(2, 0, 'drum');
+// myFish is ['angel', 'clown', 'drum', 'mandarin', 'surgeon']
+// removed is [], no elements removed
+
+// myFish is ['angel', 'clown', 'drum', 'mandarin', 'surgeon']
+// removes 1 element from index 3
+removed = myFish.splice(3, 1);
+// myFish is ['angel', 'clown', 'drum', 'surgeon']
+// removed is ['mandarin']
+
+// myFish is ['angel', 'clown', 'drum', 'surgeon']
+// removes 1 element from index 2, and inserts 'trumpet'
+removed = myFish.splice(2, 1, 'trumpet');
+// myFish is ['angel', 'clown', 'trumpet', 'surgeon']
+// removed is ['drum']
+
+// myFish is ['angel', 'clown', 'trumpet', 'surgeon']
+// removes 2 elements from index 0, and inserts 'parrot', 'anemone' and 'blue'
+removed = myFish.splice(0, 2, 'parrot', 'anemone', 'blue');
+// myFish is ['parrot', 'anemone', 'blue', 'trumpet', 'surgeon']
+// removed is ['angel', 'clown']
+
+// myFish is ['parrot', 'anemone', 'blue', 'trumpet', 'surgeon']
+// removes 2 elements from index 2
+removed = myFish.splice(myFish.length -3, 2);
+// myFish is ['parrot', 'anemone', 'surgeon']
+// removed is ['blue', 'trumpet']
+
+const myFish = ['parrot', 'anemone', 'blue', 'trumpet', 'surgeon'];
+// removes 3 elements starting at index 2
+const removed = myFish.splice(2);
+// myFish is ['parrot', 'anemone']
+// removed is ['blue', 'trumpet', 'surgeon']
+
+ +

Specificaties

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.2.
{{SpecName('ES5.1', '#sec-15.4.4.12', 'Array.prototype.splice')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-array.prototype.splice', 'Array.prototype.splice')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.prototype.splice', 'Array.prototype.splice')}}{{Spec2('ESDraft')}} 
+ +

Browser-compatibiliteit

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("1.0")}}{{CompatGeckoDesktop("1.7")}}{{CompatIE("5.5")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Compatibiliteit met oudere versies

+ +

In JavaScript 1.2 retourneert de splice()-methode het verwijderde element, wanneer slechts één element is verwijderd (deleteCount parameter is 1); in andere gevallen retourneert de methode een array met de verwijderde elementen.

+ +
+

Ter info: De laatste browser die gebruik maakte van JavaScript 1.2 was Netscape Navigator 4, dus er kan altijd worden verwacht dat  splice() altijd een array retourneert. Dit is het geval wanneer een JavaScript-object een  length-property heeft  en een  splice()-method. {{domxref("console.log()")}} werkt op dit object als op een Array-acthig object. Het object controleren met instanceof Array retourneert false.

+
+ +

Zie ook

+ + diff --git a/files/nl/web/javascript/reference/global_objects/date/index.html b/files/nl/web/javascript/reference/global_objects/date/index.html new file mode 100644 index 0000000000..98895e0fe3 --- /dev/null +++ b/files/nl/web/javascript/reference/global_objects/date/index.html @@ -0,0 +1,266 @@ +--- +title: Date +slug: Web/JavaScript/Reference/Global_Objects/Date +tags: + - Datum + - JavaScript + - Referentie +translation_of: Web/JavaScript/Reference/Global_Objects/Date +--- +
{{JSRef}}
+ +

Creëert een JavaScript Date instantie die een enkel punt in tijd voorstelt. Date objecten zijn gebaseerd op een tijdwaarde die gelijk staat aan het aantal milliseconden sinds 1 Januari, 1970 UTC.

+ +

Syntax

+ +
new Date();
+new Date(value);
+new Date(dateString);
+new Date(year, month[, day[, hour[, minutes[, seconds[, milliseconds]]]]]);
+
+ +
+

NB: JavaScript Date kan enkel worden geïnstantieerd door JavaScript Date als een constructor aan te roepen: het aanroepen als een gewone functie (bijv. zonder de {{jsxref("Operators/new", "new")}} operator) zal een string terug geven in plaats van een Date object; anders dan andere JavaScript object types, hebben JavaScript Date objecten geen letterlijke syntax.

+
+ +

Parameters

+ +
+

NB: Indien Date wordt aangeroepen als een constructor met meer dan een argument, als waarden groter zijn dan hun logische reeks (bij. 13 wordt gegeven als waarde voor de maand of 70 voor als waarde voor de minuut), wordt de naastgelegen waarde aangepast. Bijvoorbeeld new Date(2013, 13, 1) staat gelijk aan new Date(2014, 1, 1), beide creëren een datum voor 2014-02-01 (let er op dat de maand vanaf 0 telt). Dit geldt ook voor andere waarden: new Date(2013, 2, 1, 0, 70) is gelijk aan new Date(2013, 2, 1, 1, 10) en beide creëren een datum voor 2013-03-01T01:10:00.

+
+ +
+

NB: Waar Date wordt aangeroepen als een constructor met meer dan een argument, staan de opgegeven argumenten voor lokale tijd. Als UTC gewenst is, gebruik dan new Date({{jsxref("Date.UTC()", "Date.UTC(...)")}}) met dezelfde argumenten.

+
+ +
+
value
+
Numerieke waarde die het aantal milliseconden voorstelt vanaf 1 Januari 1970 00:00:00 UTC (Unix Tijdperk; maar hou er rekening mee dat de meeste Unix tijd functies in seconden tellen).
+
dateString
+
Tekstuele weergave van de datum. De tekst moet een formaat hebben dat wordt herkend door de {{jsxref("Date.parse()")}} methode (IETF-compliant RFC 2822 timestamps en ook een versie van ISO8601). +
+

Note: Het parsen van datumstrings met de Date constructor (en Date.parse, deze zijn gelijkwaardig) wordt sterk afgeraden door de verschillen en inconsistenties van browsers.

+
+
+
year
+
Numerieke voorstelling van het jaar. Waarden van 0 tot 99 komen overeen met de jaren 1900 tot 1999. Zie het {{anch("Two_digit_years_map_to_1900_-_1999", "voorbeeld beneden")}}.
+
month
+
Numerieke voorstelling van de maand, beginnend met 0 voor januari tot 11 voor december.
+
day
+
Optioneel. Numerieke voorstelling van de dag van de maand.
+
hour
+
Optioneel. Numerieke voorstelling van het uur van de dag.
+
minute
+
Optioneel. Numerieke voorstelling van het minuut segment van een tijd.
+
second
+
Optioneel. Numerieke voorstelling van het seconde segment van een tijd.
+
millisecond
+
Optioneel. Numerieke voorstelling van het milliseconde segment van een tijd.
+
+ +

Omschrijving

+ + + +

Eigenschappen

+ +
+
{{jsxref("Date.prototype")}}
+
Staat het toe om eigenschappen toe te voegen aan het JavaScript Date object.
+
Date.length
+
De waarde van Date.length is 7. Dit is het aantal argumenten wat door de constructor wordt verwerkt.
+
+ +

Methodes

+ +
+
{{jsxref("Date.now()")}}
+
Geeft de numerieke waarde van de huidige tijd - het aantal milliseconden verlopen sinds 1 Januari 1970 00:00:00 UTC.
+
{{jsxref("Date.parse()")}}
+
Verwerkt een tekstuele representaie van een datum en geeft het aantal milliseconden terug vanaf 1 Januari, 1970, 00:00:00, UTC. +
+

Note: Het parsen van datumstrings met de Date constructor (en Date.parse, deze zijn gelijk) wordt sterk afgeraden door de verschillen en inconsistenties van browsers.

+
+
+
{{jsxref("Date.UTC()")}}
+
Accepteert de zelfde parameters als de langste vorm van de constructor (ofwel 2 tot 7) en geeft het aantal milliseconden terug vanaf 1 Januari, 1970, 00:00:00 UTC.
+
+ +

JavaScript Date instanties

+ +

Alle Date instanties erven van {{jsxref("Date.prototype")}}. Het prototype object van de Date constructor kan aangepast worden om alle Date instanties te beïnvloeden.

+ +

Date.prototype Methodes

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

Voorbeelden

+ +

Verschillende manieren om een Date object te creëeren

+ +

De volgende voorbeelden tonen verschillende manieren om Javascript datums te creëren:

+ +
+

Note: Het parsen van datumstrings met de Date constructor (en Date.parse, deze zijn gelijk) wordt sterk afgeraden vanwege de verschillen en inconsistenties van browsers.

+
+ +
var vandaag = new Date();
+var verjaardag = new Date('December 17, 1995 03:24:00');
+var verjaardag = new Date('1995-12-17T03:24:00');
+var verjaardag = new Date(1995, 11, 17);
+var verjaardag = new Date(1995, 11, 17, 3, 24, 0);
+
+ +

Tweegetals jaren worden getransformeerd tot  1900-1999

+ +

Om datums tussen de jaren 0 en 99 te creëeren en te verkrijgen, horen {{jsxref("Date.prototype.setFullYear()")}} en {{jsxref("Date.prototype.getFullYear()")}} gebruikt te worden.

+ +
var date = new Date(98, 1); // Sun Feb 01 1998 00:00:00 GMT+0000 (GMT)
+
+// Verouderde methode, 98 wordt hier naar 1998 omgezet
+date.setYear(98);           // Sun Feb 01 1998 00:00:00 GMT+0000 (GMT)
+
+date.setFullYear(98);       // Sat Feb 01 0098 00:00:00 GMT+0000 (BST)
+
+ +

Verstreken tijd berekenen

+ +

De volgende voorbeelden tonen hoe het mogelijk is om te bepalen hoeveel tijd, in milliseconden, er is verstreken tussen twee Javascript datums.

+ +

In verband met het de mogelijke verschillen in lengtes van dagen (door de overgangen tussen zomer- en wintertijd), maanden en jaren, kunnen er problemen optreden als wordt geprobeerd verschillen te bepalen die groter zijn dan uren, minuten en seconden. Het wordt aangeraden eerst grondig onderzoek hiernaar te doen, alvorens dit te proberen.

+ +
// met Date objecten
+var start = Date.now();
+
+// de gebeurtenis om te meten hoort hier:
+doeIetsVoorEenLangePeriode();
+var einde = Date.now();
+var verstreken = einde - start; // verstreken tijd in milliseconden
+
+ +
// met ingebouwde methodes
+var start = new Date();
+
+// de gebeurtenis om te meten hoort hier:
+doeIetsVoorEenLangePeriode();
+var einde = new Date();
+var verstreken = einde.getTime() - start.getTime(); // verstreken tijd in milliseconden
+
+ +
// om een functie te testen en de return waarde terug te krijgen
+function printVerstrekenTijd(fTest) {
+  var nStartTijd = Date.now(),
+      vReturn = fTest(),
+      nEindTijd = Date.now();
+
+  console.log('Verstreken tijd: ' + String(nEindTijd - nStartTijd) + ' milliseconden');
+  return vReturn;
+}
+
+var jouwFunctieReturn = printVerstrekenTijd(jouwFunctie);
+
+ +
+

NB: In browsers die ondersteuning bieden voor {{domxref("window.performance", "Web Performance API", "", 1)}}'s hoge resolutie tijdsfunctionaliteiten, kan {{domxref("Performance.now()")}} meer betrouwbare en preciezere metingen opleveren dan {{jsxref("Date.now()")}} kan.

+
+ +

Aantal seconden sinds Unix Epoch

+ +
var seconden = Math.floor(Date.now() / 1000);
+ +

In dit geval is het belangrijk een geheel getal te retourneren (eenvoudige deling is niet toereikend), waarbij het gaat het aantal feitelijk verstreken seconden (daarom gebruikt deze code {{jsxref("Math.floor()")}} en niet {{jsxref("Math.round()")}}).

+ +

Specificaties

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificatieStatusCommentaar
{{SpecName('ESDraft', '#sec-date-objects', 'Date')}}{{Spec2('ESDraft')}} 
{{SpecName('ES6', '#sec-date-objects', 'Date')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-15.9', 'Date')}}{{Spec2('ES5.1')}} 
{{SpecName('ES1')}}{{Spec2('ES1')}}Initiële definitie. Geïmplementeerd in JavaScript 1.1.
+ +

Browser compatibiliteit

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

[1] Some browsers can have issues when parsing dates: 3/14/2012 blog from danvk Comparing FF/IE/Chrome on Parsing Date Strings

+ +

[2] ISO8601 Date Format is not supported in Internet Explorer 8, and other version can have issues when parsing dates

diff --git a/files/nl/web/javascript/reference/global_objects/function/apply/index.html b/files/nl/web/javascript/reference/global_objects/function/apply/index.html new file mode 100644 index 0000000000..51428929f1 --- /dev/null +++ b/files/nl/web/javascript/reference/global_objects/function/apply/index.html @@ -0,0 +1,258 @@ +--- +title: Function.prototype.apply() +slug: Web/JavaScript/Reference/Global_Objects/Function/apply +translation_of: Web/JavaScript/Reference/Global_Objects/Function/apply +--- +
{{JSRef}}
+ +

De apply() methode roept een functie aan met een gegeven this waarde en argumenten gedefineerd als een array (of een array-achtig object).

+ +
+

Let op: Hoewel de syntax van deze functie vrijwel gelijk is aan die van {{jsxref("Function.call", "call()")}}, is het fundamentele verschil met call() dat deze een lijst van argumenten accepteert, terwijl apply() een enkele array van argumenten verwacht.

+
+ +

Syntax

+ +
fun.apply(thisArg, [argsArray])
+ +

Parameters

+ +
+
thisArg
+
De waarde van this die aan de call voor fun wordt meegegeven. Hou er rekening mee dat dit mogelijk niet de waarde is die de methode ziet: Als de methode gedefineerd is in non-strict mode code, dan zullen null en undefined worden vervangen met het globale object en primitieve waardes worden omgezet naar objecten (boxed).
+
argsArray
+
Een array-achtig object met de argumenten waarmee fun moet worden aangeroepen, of {{jsxref("null")}} of {{jsxref("undefined")}} als er geen argumenten worden gegeven. Vanaf ECMAScript 5  kunnen deze argumenten een generiek array-achtig object zijn in plaats van een array. Hieronder meer informatie over {{anch("Browser_compatibility", "browser compatibiliteit")}}.
+
+ +

Return waarde

+ +

Het resultaat van de aanroep met de gegeven this waarde en argumenten.

+ +

Omschrijving

+ +

Het is mogelijk om een ander this object toe te wijzen indien je een bestaande functie aanroept. this verwijst naar het huidige object, het object dat de aanroep doet. Met apply kun je een methode eenmaal schrijven en het dan door overerving gebruiken in een ander object, zonder dat je de methode hoeft te herschrijven voor het nieuwe object.

+ +

Apply heeft veel overeenkomsten met {{jsxref("Function.call", "call()")}} maar heeft voor argumenten een andere notatie. je kunt een array van argumenten meegeven in plaats van een benoemde set aan argumenten. Met apply kun je zowel een array literal (bijv. fun.apply(this, ['eat', 'bananas'])) gebruiken als een {{jsxref("Array")}} object (bijv. fun.apply(this, new Array('eat', 'bananas'))).

+ +

Je kunt ook {{jsxref("Functions/arguments", "arguments")}} meegeven als argsArray parameter. arguments is een locale variabele of functie, en kan gebruikt worden voor alle ongespecificeerde argumenten voor het aan te roepen object. Dit houdt in dat je niet precies hoeft te weten welke argumenten nodig zijn voor het aan te roepen object als je apply() gebruikt. Het aan te roepen object is vervolgens verantwoordelijk voor de afhandeling van de argumenten.

+ +

Vanaf de 5e editie van ECMAScript kun je ook een willekeurig array-achtig object gebruiken, wat inhoud dat het een length en getallen met bereik (0 ... length-1) als properties heeft. Je kunt bijvoorbeeld een {{domxref("NodeList")}} of een op maat gemaakt object (zoals: { 'length': 2, '0': 'eat', '1': 'bananas' }) gebruiken.

+ +
+

Let op: De meeste browsers, waaronder Chrome 14 en Internet Explorer 9, ondersteunen array-achtige objecten nog niet. Deze zullen een exceptie geven als je het toch probeert.

+
+ +

Voorbeelden

+ +

Apply gebruiken om constructors te ketenen

+ +

Apply kan gebruikt worden om {{jsxref("Operators/new", "constructors", "", 1)}} voor een object aan elkaar te ketenen, gelijk aan de werkwijze in java. In het volgende voorbeeld maken we een globale {{jsxref("Function")}} methode genaamd construct, welke je in staat stelt om een array-achtig object te gebruiken in plaats van een lijst van argumenten.

+ +
Function.prototype.construct = function (aArgs) {
+  var oNew = Object.create(this.prototype);
+  this.apply(oNew, aArgs);
+  return oNew;
+};
+
+ +
+

Let op: De Object.create() methode die hierboven gebruikt wordt is vrij nieuw. Voor een alternatieve methode die gebruik maakt van closures kun je onderstaande voorbeeld ook gebruiken:

+ +
Function.prototype.construct = function(aArgs) {
+  var fConstructor = this, fNewConstr = function() {
+    fConstructor.apply(this, aArgs);
+  };
+  fNewConstr.prototype = fConstructor.prototype;
+  return new fNewConstr();
+};
+
+ +

Voorbeeld gebruik:

+ +
function MyConstructor() {
+  for (var nProp = 0; nProp < arguments.length; nProp++) {
+    this['property' + nProp] = arguments[nProp];
+  }
+}
+
+var myArray = [4, 'Hello world!', false];
+var myInstance = MyConstructor.construct(myArray);
+
+console.log(myInstance.property1);                // logs 'Hello world!'
+console.log(myInstance instanceof MyConstructor); // logs 'true'
+console.log(myInstance.constructor);              // logs 'MyConstructor'
+
+ +
+

Let op: Deze niet native Function.construct methode zal niet werken met sommige native constructors  (zoals {{jsxref("Date")}}, bij voorbeeld). In deze gevallen gebruik je de {{jsxref("Function.prototype.bind")}} methode (bij voorbeeld, stel je een array als de volgende voor, te gebruiken met {{jsxref("Global_Objects/Date", "Date")}} constructor: [2012, 11, 4]; in dit geval schrijf je bijvoorbeeld: new (Function.prototype.bind.apply(Date, [null].concat([2012, 11, 4])))() — Hoewel dit werkt is dit in meerdere opzichten een kwetsbare manier die niet in productie gebruikt zou moeten worden).

+
+ +

Gebruik van apply en ingebouwde functies

+ +

Slim gebruik van apply geeft de mogelijkheid om standaard javascript functies te gebruiken voor handelingen die anders in een loop zouden gebeuren. Als voorbeeld gaan we Math.max/Math.min gebruiken wat de maximum en minimum waardes zijn in een array.

+ +
// min/max number in an array
+var numbers = [5, 6, 2, 3, 7];
+
+// using Math.min/Math.max apply
+var max = Math.max.apply(null, numbers);
+// This about equal to Math.max(numbers[0], ...)
+// or Math.max(5, 6, ...)
+
+var min = Math.min.apply(null, numbers);
+
+// vs. simple loop based algorithm
+max = -Infinity, min = +Infinity;
+
+for (var i = 0; i < numbers.length; i++) {
+  if (numbers[i] > max) {
+    max = numbers[i];
+  }
+  if (numbers[i] < min) {
+    min = numbers[i];
+  }
+}
+
+ +

Maar pas op: door apply op deze manier te gebruiken loop je het risico over de maximum argument limiet van JavaScript's engine heen te gaan. De consequenties van het gebruik van apply op een functie met te veel argumenten (denk aan meer dan tienduizen argumenten) varieren tussen de verschillende engines (JavaScriptCore heeft een hard-coded  argument limiet van 65536), omdat de limiet (en het gedrag bij extreem grote hoeveelheden objecten) niet is opgenomen in een standaard. Sommige engines zullen een exceptie opgooien, anderen kunnen mogelijk zelfs het aantal argumenten afkappen bij het maximum. Als je array toch het risico loopt te groeien voorbij de limiet, kun je beter een hybriede implementatie maken: voer je functie uit over stukken van een array, bijvoorbeeld: 

+ +
function minOfArray(arr) {
+  var min = Infinity;
+  var QUANTUM = 32768;
+
+  for (var i = 0, len = arr.length; i < len; i += QUANTUM) {
+    var submin = Math.min.apply(null,
+                                arr.slice(i, Math.min(i+QUANTUM, len)));
+    min = Math.min(submin, min);
+  }
+
+  return min;
+}
+
+var min = minOfArray([5, 6, 2, 3, 7]);
+
+ +

Gebruik van apply bij "monkey-patching"

+ +

Apply kan enorm nuttig zijn bij het monkey-patchen van browser-eigen-  of framework-functies. Met bijvoorbeeld de someobject.foo functie, kun je de functie aanpassen op de volgende, ietwat smerige manier:

+ +
var originalfoo = someobject.foo;
+someobject.foo = function() {
+  // Do stuff before calling function
+  console.log(arguments);
+  // Call the function as it would have been called normally:
+  originalfoo.apply(this, arguments);
+  // Run stuff after, here.
+}
+
+ +

Specificaties

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Initiele definitie. Geimplementeerd in JavaScript 1.3.
{{SpecName('ES5.1', '#sec-15.3.4.3', 'Function.prototype.apply')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-function.prototype.apply', 'Function.prototype.apply')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-function.prototype.apply', 'Function.prototype.apply')}}{{Spec2('ESDraft')}}
+ +

Browser compatibiliteit

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
ES 5.1 generic array-like object as {{jsxref("Functions/arguments", "arguments")}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("2.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
ES 5.1 generic array-like object as {{jsxref("Functions/arguments", "arguments")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("2.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

Zie ook

+ + diff --git a/files/nl/web/javascript/reference/global_objects/function/call/index.html b/files/nl/web/javascript/reference/global_objects/function/call/index.html new file mode 100644 index 0000000000..aee4b67e7f --- /dev/null +++ b/files/nl/web/javascript/reference/global_objects/function/call/index.html @@ -0,0 +1,225 @@ +--- +title: Function.prototype.call() +slug: Web/JavaScript/Reference/Global_Objects/Function/call +tags: + - Functie + - JavaScript + - Méthode +translation_of: Web/JavaScript/Reference/Global_Objects/Function/call +--- +
{{JSRef}}
+ +

De call() methode roept een functie aan met een gegeven this waarde en afzonderlijk gedefineerde argumenten.

+ +
+

Note: Hoewel de syntax van deze functie vrijwel gelijk is aan die van {{jsxref("Function.prototype.apply", "apply()")}}, zit er een essentieel verschil tussen deze twee. De call() methode accepteert een argumentenlijst, terwijl apply() een enkele array met argumenten accepteert.

+
+ +

Syntax

+ +
function.call(thisArg[, arg1[, arg2[, ...]]])
+ +

Parameters

+ +
+
thisArg
+
De waarde van this die aan de call voor function wordt meegegeven. Houd er rekening mee dat dit mogelijk niet de waarde is die de methode ziet: Als de methode gedefineerd is in {{jsxref("Functions_and_function_scope/Strict_mode", "non-strict mode", "", 1)}} code, dan zullen {{jsxref("Global_Objects/null", "null")}} en {{jsxref("Global_Objects/undefined", "undefined")}} worden vervangen met het globale object en primitieve waardes worden omgezet naar objecten.
+
arg1, arg2, ...
+
De argumenten voor het object.
+
+ +

Return waarde

+ +

Het resultaat van het aanroepen van de functie met de gespecificeerde this waarde en argumenten.

+ +

Omschrijving

+ +

De call() methode staat het toe dat een functie of methode van een object om te worden toegewezen en aangeroepen voor een ander object.

+ +

Een ander this object worden toegewezen als er een bestaande functie wordt aangeroepen. this verwijst in principe naar het huidige object, het object wat de aanroep doet. Met call kun je een methode eenmaal schrijven en dan door overerving gebruiken in een ander object, zonder dat je de methode hoeft te herschrijven voor het nieuwe object.

+ +

Voorbeelden

+ +

call gebruiken om constructors aan elkaar te ketenen voor een object

+ +

call kan gebruikt worden om constructors voor een object aan elkaar te ketenen, vergelijkbaar met de werkwijze in Java. In het volgende voorbeeld is de constructor voor het Product object gedefineerd met twee parameters; name en price. De twee andere functies, Food en Toy, roepen Product aan en geven thisname en price mee. Product initializeert de eigenschappen name en price, en deze gespecializeerde functies defineren de category

+ +
function Product(name, price) {
+  this.name = name;
+  this.price = price;
+
+  if (price < 0) {
+    throw RangeError('Cannot create product ' +
+                      this.name + ' with a negative price');
+  }
+}
+
+function Food(name, price) {
+  Product.call(this, name, price);
+  this.category = 'food';
+}
+
+function Toy(name, price) {
+  Product.call(this, name, price);
+  this.category = 'toy';
+}
+
+var cheese = new Food('feta', 5);
+var fun = new Toy('robot', 40);
+
+ +

call gebruiken om een anonieme functie aan te roepen

+ +

In dit voorbeeld hebben we een anonieme functie, en gebruiken we call om deze aan te roepen voor elk object in een array. Het voornaamste doel van de anonieme functie is het toevoegen van een print functie aan elk object in de array. Het object meegeven als this waarde is niet strict noodzakelijk, maar laat wel de werking zien.

+ +
var animals = [
+  { species: 'Lion', name: 'King' },
+  { species: 'Whale', name: 'Fail' }
+];
+
+for (var i = 0; i < animals.length; i++) {
+  (function(i) {
+    this.print = function() {
+      console.log('#' + i + ' ' + this.species
+                  + ': ' + this.name);
+    }
+    this.print();
+  }).call(animals[i], i);
+}
+
+ +

Call gebruiken om een functie aan te roepen en een context te geven aan 'this'.

+ +

In het onderstaande voorbeeld zal de waarde van this gebonden zijn aan het object obj wanneer we greet aanroepen.

+ +
function greet() {
+  var reply = [this.person, 'is An Awesome', this.role].join(' ');
+  console.log(reply);
+}
+
+var obj = {
+  person: 'Douglas Crockford', role: 'Javascript Developer'
+};
+
+greet.call(obj); // Douglas Crockford Is An Awesome Javascript Developer
+
+ +

Call gebruiken om een functie aan te roepen zonder eerste argument

+ +

In het onderstaande voorbeeld roepen we de display functie aan zonder het eerste argument mee te geven. Als het eerste argument niet is meegegeven zal this worden gebonden aan het globale object.

+ +
var sData = 'Wisen';
+
+function display() {
+  console.log('sData value is %s ', this.sData);
+}
+
+display.call();  // sData value is Wisen
+ +
+

Note: De waarde van this is undefined in strict mode. Zie onderstaand.

+
+ +
'use strict';
+
+var sData = 'Wisen';
+
+function display() {
+  console.log('sData value is %s ', this.sData);
+}
+
+display.call(); // Cannot read the property of 'sData' of undefined
+ +

Specificaties

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initiele definitie. Geimplementeerd in JavaScript 1.3.
{{SpecName('ES5.1', '#sec-15.3.4.4', 'Function.prototype.call')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-function.prototype.call', 'Function.prototype.call')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-function.prototype.call', 'Function.prototype.call')}}{{Spec2('ESDraft')}}
+ +

Browser compatibility

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

See also

+ + diff --git a/files/nl/web/javascript/reference/global_objects/function/index.html b/files/nl/web/javascript/reference/global_objects/function/index.html new file mode 100644 index 0000000000..9cb0571d13 --- /dev/null +++ b/files/nl/web/javascript/reference/global_objects/function/index.html @@ -0,0 +1,236 @@ +--- +title: Function +slug: Web/JavaScript/Reference/Global_Objects/Function +tags: + - Constructor + - Function + - JavaScript + - NeedsTranslation + - TopicStub +translation_of: Web/JavaScript/Reference/Global_Objects/Function +--- +
{{JSRef}}
+ +

The Function constructor creates a new Function object. In JavaScript every function is actually a Function object.

+ +

Syntax

+ +
new Function ([arg1[, arg2[, ...argN]],] functionBody)
+ +

Parameters

+ +
+
arg1, arg2, ... argN
+
Names to be used by the function as formal argument names. Each must be a string that corresponds to a valid JavaScript identifier or a list of such strings separated with a comma; for example "x", "theValue", or "a,b".
+
functionBody
+
A string containing the JavaScript statements comprising the function definition.
+
+ +

Description

+ +

Function objects created with the Function constructor are parsed when the function is created. This is less efficient than declaring a function with a function expression or function statement and calling it within your code, because such functions are parsed with the rest of the code.

+ +

All arguments passed to the function are treated as the names of the identifiers of the parameters in the function to be created, in the order in which they are passed.

+ +
+

Note: Functions created with the Function constructor do not create closures to their creation contexts; they always are created in the global scope. When running them, they will only be able to access their own local variables and global ones, not the ones from the scope in which the Function constructor was called. This is different from using {{jsxref("eval")}} with code for a function expression.

+
+ +

Invoking the Function constructor as a function (without using the new operator) has the same effect as invoking it as a constructor.

+ +

Properties and Methods of Function

+ +

The global Function object has no methods or properties of its own, however, since it is a function itself it does inherit some methods and properties through the prototype chain from {{jsxref("Function.prototype")}}.

+ +

Function prototype object

+ +

Properties

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

Methods

+ +
{{page('/en-US/docs/JavaScript/Reference/Global_Objects/Function/prototype', 'Methods')}}
+ +

Function instances

+ +

Function instances inherit methods and properties from {{jsxref("Function.prototype")}}. As with all constructors, you can change the constructor's prototype object to make changes to all Function instances.

+ +

Examples

+ +

Specifying arguments with the Function constructor

+ +

The following code creates a Function object that takes two arguments.

+ +
// Example can be run directly in your JavaScript console
+
+// Create a function that takes two arguments and returns the sum of those arguments
+var adder = new Function('a', 'b', 'return a + b');
+
+// Call the function
+adder(2, 6);
+// > 8
+
+ +

The arguments "a" and "b" are formal argument names that are used in the function body, "return a + b".

+ +

A recursive shortcut to massively modify the DOM

+ +

Creating functions with the Function constructor is one of the ways to dynamically create an indeterminate number of new objects with some executable code into the global scope from a function. The following example (a recursive shortcut to massively modify the DOM) is impossible without the invocation of the Function constructor for each new query if you want to avoid closures.

+ +
<!doctype html>
+<html>
+<head>
+<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
+<title>MDN Example - a recursive shortcut to massively modify the DOM</title>
+<script type="text/javascript">
+var domQuery = (function() {
+  var aDOMFunc = [
+    Element.prototype.removeAttribute,
+    Element.prototype.setAttribute,
+    CSSStyleDeclaration.prototype.removeProperty,
+    CSSStyleDeclaration.prototype.setProperty
+  ];
+
+  function setSomething(bStyle, sProp, sVal) {
+    var bSet = Boolean(sVal), fAction = aDOMFunc[bSet | bStyle << 1],
+        aArgs = Array.prototype.slice.call(arguments, 1, bSet ? 3 : 2),
+        aNodeList = bStyle ? this.cssNodes : this.nodes;
+
+    if (bSet && bStyle) { aArgs.push(''); }
+    for (
+      var nItem = 0, nLen = this.nodes.length;
+      nItem < nLen;
+      fAction.apply(aNodeList[nItem++], aArgs)
+    );
+    this.follow = setSomething.caller;
+    return this;
+  }
+
+  function setStyles(sProp, sVal) { return setSomething.call(this, true, sProp, sVal); }
+  function setAttribs(sProp, sVal) { return setSomething.call(this, false, sProp, sVal); }
+  function getSelectors() { return this.selectors; };
+  function getNodes() { return this.nodes; };
+
+  return (function(sSelectors) {
+    var oQuery = new Function('return arguments.callee.follow.apply(arguments.callee, arguments);');
+    oQuery.selectors = sSelectors;
+    oQuery.nodes = document.querySelectorAll(sSelectors);
+    oQuery.cssNodes = Array.prototype.map.call(oQuery.nodes, function(oInlineCSS) { return oInlineCSS.style; });
+    oQuery.attributes = setAttribs;
+    oQuery.inlineStyle = setStyles;
+    oQuery.follow = getNodes;
+    oQuery.toString = getSelectors;
+    oQuery.valueOf = getNodes;
+    return oQuery;
+  });
+})();
+</script>
+</head>
+
+<body>
+
+<div class="testClass">Lorem ipsum</div>
+<p>Some text</p>
+<div class="testClass">dolor sit amet</div>
+
+<script type="text/javascript">
+domQuery('.testClass')
+  .attributes('lang', 'en')('title', 'Risus abundat in ore stultorum')
+  .inlineStyle('background-color', 'black')('color', 'white')('width', '100px')('height', '50px');
+</script>
+</body>
+
+</html>
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.3', 'Function')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-function-objects', 'Function')}}{{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/nl/web/javascript/reference/global_objects/index.html b/files/nl/web/javascript/reference/global_objects/index.html new file mode 100644 index 0000000000..7395446f35 --- /dev/null +++ b/files/nl/web/javascript/reference/global_objects/index.html @@ -0,0 +1,183 @@ +--- +title: Standard built-in objects +slug: Web/JavaScript/Reference/Global_Objects +tags: + - JavaScript + - NeedsTranslation + - Objects + - 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/nl/web/javascript/reference/global_objects/isfinite/index.html b/files/nl/web/javascript/reference/global_objects/isfinite/index.html new file mode 100644 index 0000000000..eaee2238aa --- /dev/null +++ b/files/nl/web/javascript/reference/global_objects/isfinite/index.html @@ -0,0 +1,95 @@ +--- +title: isFinite() +slug: Web/JavaScript/Reference/Global_Objects/isFinite +tags: + - JavaScript +translation_of: Web/JavaScript/Reference/Global_Objects/isFinite +--- +
{{jsSidebar("Objects")}}
+ +

De globale functie isFinite() bepaalt of de doorgegeven waarde een eindig getal is. Wanneer nodig wordt de parameter eerst omgezet naar een getal.

+ +

Syntaxis

+ +
isFinite(testValue)
+ +

Parameters

+ +
+
testValue
+
De waarde die op eindigheid wordt getest.
+
+ +

Retourwaarde

+ +

false als de waarde positief is of negatief {{jsxref("Infinity")}} of {{jsxref("NaN")}}; anders, true.

+ +

Beschrijving

+ +

isFinite is een top-levelfunctie en is niet geassocieerd met een object.

+ +

Deze functie is te gebruiken om te bepalen of een getal eindig is. De functie isFinite controleert het getal in het argument. Als het argument NaN is, positief oneindig, of negatief oneindig, geeft deze methode false terug; anders geeft deze true terug.

+ +

Voorbeelden

+ +
isFinite(Infinity);  // false
+isFinite(NaN);       // false
+isFinite(-Infinity); // false
+
+isFinite(0);         // true
+isFinite(2e64);      // true
+isFinite(910);       // true
+
+isFinite(null);      // true, met het robuustere Number.isFinite(null) zou
+                     // deze waarde false zijn geweest.
+
+isFinite('0');       // true, met het robuustere Number.isFinite("0") zou
+                     // deze waarde false zijn geweest.
+
+ +

Specificaties

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificatieStatusOpmerking
{{SpecName('ES3')}}{{Spec2('ES3')}}Initiële definitie.
{{SpecName('ES5.1', '#sec-15.1.2.5', 'isFinite')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-isfinite-number', 'isFinite')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-isfinite-number', 'isFinite')}}{{Spec2('ESDraft')}}
+ +

Browsercompatibiliteit

+ + + +

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

+ +

Zie ook

+ + diff --git a/files/nl/web/javascript/reference/global_objects/null/index.html b/files/nl/web/javascript/reference/global_objects/null/index.html new file mode 100644 index 0000000000..4a5abdaa2d --- /dev/null +++ b/files/nl/web/javascript/reference/global_objects/null/index.html @@ -0,0 +1,124 @@ +--- +title: 'null' +slug: Web/JavaScript/Reference/Global_Objects/null +translation_of: Web/JavaScript/Reference/Global_Objects/null +--- +
{{jsSidebar("Objects")}}
+ +

De waarde null representeert het moedwillig weglaten, of de bedoelde afwezigheid van welk object of waarde dan ook. Het is een van JavaScript's {{Glossary("Primitive", "primitive values")}}.

+ +

Syntax

+ +
null 
+ +

Beschrijving

+ +

De waarde null wordt letterlijk geschreven als null (het is geen idenfifier voor een eigenschap van de global object zoals  {{jsxref("Global_Objects/undefined","undefined")}} wel kan zijn). In APIs, wordt null vaak verkregen op plekken waar een object mag worden verwacht, maar waar tegelijk geen object relevant is . Wanneer op null of undefined wordt gecontroleerd, wees dan bewust van de  verschillen tussen equality (==) en identity (===) operators (type-conversie wordt via de eerste bereikt).

+ +
// foo does not exist. It is not defined and has never been initialized:
+> foo
+"ReferenceError: foo is not defined"
+
+// foo is known to exist now but it has no type or value:
+> var foo = null; foo
+"null"
+
+ +

Verschil tussen null en undefined

+ +
typeof null        // object (bug in ECMAScript, should be null)
+typeof undefined   // undefined
+null === undefined // false
+null  == undefined // true
+
+ +

Specificaties

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificatieStatusCommentaar
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition.
{{SpecName('ES5.1', '#sec-4.3.11', 'null value')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-null-value', 'null value')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-null-value', 'null value')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibiliteit

+ +

{{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}}
+
+ +

Zie ook

+ + diff --git a/files/nl/web/javascript/reference/global_objects/object/index.html b/files/nl/web/javascript/reference/global_objects/object/index.html new file mode 100644 index 0000000000..52aaef2901 --- /dev/null +++ b/files/nl/web/javascript/reference/global_objects/object/index.html @@ -0,0 +1,226 @@ +--- +title: Object +slug: Web/JavaScript/Reference/Global_Objects/Object +tags: + - Constructor + - JavaScript + - NeedsTranslation + - Object + - TopicStub +translation_of: Web/JavaScript/Reference/Global_Objects/Object +--- +
{{JSRef}}
+ +

The Object constructor creates an object wrapper.

+ +

Syntax

+ +
// Object initialiser or literal
+{ [ nameValuePair1[, nameValuePair2[, ...nameValuePairN] ] ] }
+
+// Called as a constructor
+new Object([value])
+ +

Parameters

+ +
+
nameValuePair1, nameValuePair2, ... nameValuePairN
+
Pairs of names (strings) and values (any value) where the name is separated from the value by a colon.
+
value
+
Any value.
+
+ +

Description

+ +

The Object constructor creates an object wrapper for the given value. If the value is {{jsxref("null")}} or {{jsxref("undefined")}}, it will create and return an empty object, otherwise, it will return an object of a Type that corresponds to the given value. If the value is an object already, it will return the value.

+ +

When called in a non-constructor context, Object behaves identically to new Object().

+ +

See also the object initializer / literal syntax.

+ +

Properties of the Object constructor

+ +
+
Object.length
+
Has a value of 1.
+
{{jsxref("Object.prototype")}}
+
Allows the addition of properties to all objects of type Object.
+
+ +

Methods of the Object constructor

+ +
+
{{jsxref("Object.assign()")}}
+
Creates a new object by copying the values of all enumerable own properties from one or more source objects to a target object.
+
{{jsxref("Object.create()")}}
+
Creates a new object with the specified prototype object and properties.
+
{{jsxref("Object.defineProperty()")}}
+
Adds the named property described by a given descriptor to an object.
+
{{jsxref("Object.defineProperties()")}}
+
Adds the named properties described by the given descriptors to an object.
+
{{jsxref("Object.entries()")}} {{experimental_inline}}
+
Returns an array of a given object's own enumerable property [key, value] pairs.
+
{{jsxref("Object.freeze()")}}
+
Freezes an object: other code can't delete or change any properties.
+
{{jsxref("Object.getOwnPropertyDescriptor()")}}
+
Returns a property descriptor for a named property on an object.
+
{{jsxref("Object.getOwnPropertyNames()")}}
+
Returns an array containing the names of all of the given object's own enumerable and non-enumerable properties.
+
{{jsxref("Object.getOwnPropertySymbols()")}}
+
Returns an array of all symbol properties found directly upon a given object.
+
{{jsxref("Object.getPrototypeOf()")}}
+
Returns the prototype of the specified object.
+
{{jsxref("Object.is()")}}
+
Compares if two values are distinguishable (ie. the same)
+
{{jsxref("Object.isExtensible()")}}
+
Determines if extending of an object is allowed.
+
{{jsxref("Object.isFrozen()")}}
+
Determines if an object was frozen.
+
{{jsxref("Object.isSealed()")}}
+
Determines if an object is sealed.
+
{{jsxref("Object.keys()")}}
+
Returns an array containing the names of all of the given object's own enumerable properties.
+
{{jsxref("Object.observe()")}} {{non-standard_inline}}
+
Asynchronously observes changes to an object.
+
{{jsxref("Object.getNotifier()")}} {{non-standard_inline}}
+
Get a notifier with which to create object changes manually.
+
{{jsxref("Object.preventExtensions()")}}
+
Prevents any extensions of an object.
+
{{jsxref("Object.seal()")}}
+
Prevents other code from deleting properties of an object.
+
{{jsxref("Object.setPrototypeOf()")}}
+
Sets the prototype (i.e., the internal [[Prototype]] property)
+
{{jsxref("Object.unobserve()")}} {{non-standard_inline}}
+
Unobserves changes to an object.
+
{{jsxref("Object.values()")}} {{experimental_inline}}
+
Returns an array of a given object's own enumerable values.
+
+ +

Object instances and Object prototype object

+ +

All objects in JavaScript are descended from Object; all objects inherit methods and properties from {{jsxref("Object.prototype")}}, although they may be overridden. For example, other constructors' prototypes override the constructor property and provide their own toString() methods. Changes to the Object prototype object are propagated to all objects unless the properties and methods subject to those changes are overridden further along the prototype chain.

+ +

Properties

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

Methods

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

Examples

+ +

Using Object given undefined and null types

+ +

The following examples store an empty Object object in o:

+ +
var o = new Object();
+
+ +
var o = new Object(undefined);
+
+ +
var o = new Object(null);
+
+ +

Using Object to create Boolean objects

+ +

The following examples store {{jsxref("Boolean")}} objects in o:

+ +
// equivalent to o = new Boolean(true);
+var o = new Object(true);
+
+ +
// equivalent to o = new Boolean(false);
+var o = new Object(Boolean());
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.2', 'Object')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-object-objects', 'Object')}}{{Spec2('ES6')}}Added Object.assign, Object.getOwnPropertySymbols, Object.setPrototypeOf
{{SpecName('ESDraft', '#sec-object-objects', 'Object')}}{{Spec2('ESDraft')}}Added Object.entries and Object.values.
+ +

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/nl/web/javascript/reference/global_objects/object/prototype/index.html b/files/nl/web/javascript/reference/global_objects/object/prototype/index.html new file mode 100644 index 0000000000..9f3672466b --- /dev/null +++ b/files/nl/web/javascript/reference/global_objects/object/prototype/index.html @@ -0,0 +1,240 @@ +--- +title: Object.prototype +slug: Web/JavaScript/Reference/Global_Objects/Object/prototype +tags: + - JavaScript + - Object + - Property +translation_of: Web/JavaScript/Reference/Global_Objects/Object +--- +
{{JSRef}}
+ +

De Object.prototype eigenschap vertegenwoordigt het {{jsxref("Object")}} prototype object.

+ +

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

+ +

Beschrijving

+ +

Alle objecten in JavaScript zijn afstammelingen van het {{jsxref("Object")}}; alle objecten erven methode's en eigenschappen van Object.prototype, althans kunnen ze overschreden worden (behalve een Object met een null prototype, i.e Object.create(null)). Bijvoorbeeld, een andere constructors' prototypes overschrijden de constructor eigenschap en voorzien hun eigen  {{jsxref("Object.prototype.toString()", "toString()")}} methode's.

+ +

Veranderingen in het Object prototype object zijn zichtbaar voor alle objecten door prototype chaining, tenzij de eigenschappen en methode's onderworpen door deze veranderingen worden overschreden verderop de prototype chain. Dit voorziet een vrij krachtig althans potentieel gevaarlijk mechanisme om het gedrag van een object te overschrijden of aan te vullen.

+ +

Eigenschappen

+ +
+
{{jsxref("Object.prototype.constructor")}}
+
Beschrijft de functie dat het object's prototype aanmaakt.
+
{{jsxref("Object.prototype.__proto__")}} {{non-standard_inline}}
+
Wijst aan het object welke was bebruikt als prototype wanneer het object was geinstantieerd.
+
{{jsxref("Object.prototype.__noSuchMethod__")}} {{non-standard_inline}}
+
Laat het toe om een functie te definieeren dat zal worden uitgevoerd wanneer een ongedefinieerd lid van een object word geroepen als een methode. 
+
{{jsxref("Object.prototype.count","Object.prototype.__count__")}} {{obsolete_inline}}
+
Used to return the number of enumerable properties directly on a user-defined object, but has been removed.
+
{{jsxref("Object.prototype.parent","Object.prototype.__parent__")}} {{obsolete_inline}}
+
Used to point to an object's context, but has been removed.
+
+ +

Methode's

+ +
+
{{jsxref("Object.prototype.__defineGetter__()")}} {{non-standard_inline}} {{deprecated_inline}}
+
Associeert een functie met een eigenschap dat, wanneer toegankelijk, een functie uitvoerd en zijn keert zijn return waarde terug.
+
{{jsxref("Object.prototype.__defineSetter__()")}} {{non-standard_inline}} {{deprecated_inline}}
+
Associeert een functie met een eigenschap dat, wanneer gezet, een functie uitvoerd dat de eigenchap veranderd.
+
{{jsxref("Object.prototype.__lookupGetter__()")}} {{non-standard_inline}} {{deprecated_inline}}
+
Keert de functie geassocieert met de gespecificieerde eigenschap door de {{jsxref("Object.prototype.__defineGetter__()", "__defineGetter__()")}} methode.
+
{{jsxref("Object.prototype.__lookupSetter__()")}} {{non-standard_inline}} {{deprecated_inline}}
+
Keert de functie geassocieert met de gespecificieerde eigenschap door de {{jsxref("Object.prototype.__defineSetter__()", "__defineSetter__()")}} method.
+
{{jsxref("Object.prototype.hasOwnProperty()")}}
+
Keert een boolean terug die aanwijst of een object dat de eigenschap bevat als een directe eigenschap van dat object en niet wordt geerfd door de prototype chain.
+
{{jsxref("Object.prototype.isPrototypeOf()")}}
+
Keert een boolean waarde terug die aanwijst of het object in de prototype chain zit van het object van waaruit deze methode is geroepen.
+
{{jsxref("Object.prototype.propertyIsEnumerable()")}}
+
Keert een boolean waarde terug die aanwijst of de ECMAScript [[Enumerable]] attribute is gezet.
+
{{jsxref("Object.prototype.toSource()")}} {{non-standard_inline}}
+
Keert een string terug die de bron van een object zijn literal, die het object waarop deze methode word op geroepen represedenteerd; je kan deze waarde gebruiken om een niew object te maken.
+
{{jsxref("Object.prototype.toLocaleString()")}}
+
Roept {{jsxref("Object.toString", "toString()")}}.
+
{{jsxref("Object.prototype.toString()")}}
+
Keert een string representatie terug van het object.
+
{{jsxref("Object.prototype.unwatch()")}} {{non-standard_inline}}
+
Verwijderd een watchpoint van een eigenschap van het object.
+
{{jsxref("Object.prototype.valueOf()")}}
+
Keert een primitive waarde terug van het gespecifieerde object.
+
{{jsxref("Object.prototype.watch()")}} {{non-standard_inline}}
+
Voegt een watchpoint toe aan de eigenschap van het object.
+
{{jsxref("Object.prototype.eval()")}} {{obsolete_inline}}
+
Used to evaluate a string of JavaScript code in the context of the specified object, but has been removed.
+
+ +

Voorbeelden

+ +

Als het gedrag van bestaande Object.prototype's methode's worden veranderd, overweeg code te injecteren door je uitbreiding in te wikkelen voor of achter de bestaande logica. Bijvoorbeeld, deze (ongeteste) code zal onvoorwaardelijk aangepaste logica uitvoeren vooralleer de ingebouwde logica of anderman's uitbreiding word uitgevoerd.

+ +

Wanneer een functie is geroepen zullen de argumenten worden gehouden in de array-achtige "variable" van de argumenten. Bijvoorbeeld, in de call "myFn(a, b, c)", zullen de argumenten binnenin myFn's lichaam 3 array elementen bevatten die coressponderen tot (a, b, c).  Wanneer prototype's met haken worden bijgewerkt, voer simpelweg deze & de argementen (de call toestand) toe aan het huidig gedrag door apply() te roepen op de functie. Dit patroon can worden gebruikt voor elk prototype, zoals Node.prototype, Function.prototype, etc.

+ +

var current = Object.prototype.valueOf; // Since my property "-prop-value" is cross-cutting and isn't always // on the same prototype chain, I want to modify Object.prototype: Object.prototype.valueOf = function() { if (this.hasOwnProperty("-prop-value") {   return this["-prop-value"];   } else {   // It doesn't look like one of my objects, so let's fall back on   // the default behavior by reproducing the current behavior as best we can.   // The apply behaves like "super" in some other languages.   // Even though valueOf() doesn't take arguments, some other hook may.   return current.apply(this, arguments);   } }

+ +

Doordat JavaScript geen sub-classe object bevat, prototype is een handige workaround om een "base class" object aan te maken van bepaalde functie's die zich gedragen als objecten. Bijvoorbeeld:

+ +
var Person = function() {
+  this.canTalk = true;
+};
+
+Person.prototype.greet = function() {
+  if (this.canTalk) {
+    console.log('Hi, I am ' + this.name);
+  }
+};
+
+var Employee = function(name, title) {
+  Person.call(this);
+  this.name = name;
+  this.title = title;
+};
+
+Employee.prototype = Object.create(Person.prototype);
+Employee.prototype.constructor = Employee;
+
+Employee.prototype.greet = function() {
+  if (this.canTalk) {
+    console.log('Hi, I am ' + this.name + ', the ' + this.title);
+  }
+};
+
+var Customer = function(name) {
+  Person.call(this);
+  this.name = name;
+};
+
+Customer.prototype = Object.create(Person.prototype);
+Customer.prototype.constructor = Customer;
+
+var Mime = function(name) {
+  Person.call(this);
+  this.name = name;
+  this.canTalk = false;
+};
+
+Mime.prototype = Object.create(Person.prototype);
+Mime.prototype.constructor = Mime;
+
+var bob = new Employee('Bob', 'Builder');
+var joe = new Customer('Joe');
+var rg = new Employee('Red Green', 'Handyman');
+var mike = new Customer('Mike');
+var mime = new Mime('Mime');
+
+bob.greet();
+// Hi, I am Bob, the Builder
+
+joe.greet();
+// Hi, I am Joe
+
+rg.greet();
+// Hi, I am Red Green, the Handyman
+
+mike.greet();
+// Hi, I am Mike
+
+mime.greet();
+
+ +

Specificaties

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificatieStatusCommentaar
{{SpecName('ES1')}}{{Spec2('ES1')}}Initiale definitie. Geimplemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.2.3.1', 'Object.prototype')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-object.prototype', 'Object.prototype')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-object.prototype', 'Object.prototype')}}{{Spec2('ESDraft')}} 
+ +

Browser ondersteuning

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
SoortChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basis Ondersteuning{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
SoortAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
+ + + + + + + +
Basis Ondersteuning 
+
{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

See also

+ + diff --git a/files/nl/web/javascript/reference/global_objects/parsefloat/index.html b/files/nl/web/javascript/reference/global_objects/parsefloat/index.html new file mode 100644 index 0000000000..e88af6c4b3 --- /dev/null +++ b/files/nl/web/javascript/reference/global_objects/parsefloat/index.html @@ -0,0 +1,168 @@ +--- +title: parseFloat() +slug: Web/JavaScript/Reference/Global_Objects/parseFloat +tags: + - JavaScript +translation_of: Web/JavaScript/Reference/Global_Objects/parseFloat +--- +
+
+
{{jsSidebar("Objects")}}
+
+
+ +

De parseFloat() functie verwerkt een string argument en geeft een  floating point nummer terug.

+ +

Syntax

+ +
parseFloat(string)
+ +

Parameters

+ +
+
string
+
Een string waarde die je wilt verwerken.
+
+ +

Omschrijving

+ +

parseFloat is een top-level functie en is niet verbonden met welk object dan ook.

+ +

parseFloat verwerkt het argument , een string, en geeft een floating point nummer terug. Als het een ander karakter tegenkomt dan een teken (+ or -), nummerieke waarde (0-9), een decimale punt , of een exponent, dan geeft het de waarde tot dat karakter terug en negeert dat karakter en alle daaropvolgende karakters. Spaties aan het begin en einde van de string zijn toegestaan.

+ +

Als het eerste karakter niet in een nummer kan worden veranderd zal parseFloat het resultaat NaN opleveren.

+ +

Voor wiskundige doeleinden, de waarde NaN is geen nummer met een radix. Je kunt de functie {{jsxref("isNaN")}} gebruiken om vast te stellen of het resultaat van parseFloat NaN is. Als NaN in een wiskundige operatie wordt gebruikt is het resultaat ook NaN.

+ +

parseFloat kan ook de waarde Infinity verwerken en het resultaat is Infinity.  Je kunt de functie  {{jsxref("isFinite")}} gebruiken om vast te stellen of het resultaat een eindig getal is (niet Infinity, -Infinity, of NaN).

+ +

Voorbeelden

+ +

parseFloat levert een nummer op

+ +

Het resultaat van de volgende voorbeelden is 3.14

+ +
parseFloat("3.14");
+parseFloat("314e-2");
+parseFloat("0.0314E+2");
+parseFloat("3.14more non-digit characters");
+
+ +

parseFloat levert NaN op

+ +

Het volgende voorbeeld heeft als resultaat NaN

+ +
parseFloat("FF2");
+
+ +

Een bondigere parse function

+ +

Soms is het handig om een bondigere manier te hebben om float waardes om te zetten, regular expressions helpen hierbij :

+ +
var filterFloat = function (value) {
+    if(/^(\-|\+)?([0-9]+(\.[0-9]+)?|Infinity)$/
+      .test(value))
+      return Number(value);
+  return NaN;
+}
+
+console.log(filterFloat('421'));               // 421
+console.log(filterFloat('-421'));              // -421
+console.log(filterFloat('+421'));              // 421
+console.log(filterFloat('Infinity'));          // Infinity
+console.log(filterFloat('1.61803398875'));     // 1.61803398875
+console.log(filterFloat('421e+0'));            // NaN
+console.log(filterFloat('421hop'));            // NaN
+console.log(filterFloat('hop1.61803398875'));  // NaN
+
+
+ +

Deze code is alleen een voorbeeld. Het accepteert geen geldige nummers zoals 1 of 5.

+ +

Specificaties

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificatieStatusCommentaar
{{SpecName('ES1')}}{{Spec2('ES1')}}Eerste definitie.
{{SpecName('ES5.1', '#sec-15.1.2.3', 'parseFloat')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-parsefloat-string', 'parseFloat')}}{{Spec2('ES6')}} 
+ +

Browser compabiliteit

+ +

{{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}}
+
+ +

Zie ook

+ + diff --git a/files/nl/web/javascript/reference/global_objects/string/index.html b/files/nl/web/javascript/reference/global_objects/string/index.html new file mode 100644 index 0000000000..a4847a7626 --- /dev/null +++ b/files/nl/web/javascript/reference/global_objects/string/index.html @@ -0,0 +1,409 @@ +--- +title: String +slug: Web/JavaScript/Reference/Global_Objects/String +tags: + - ECMAScript6 + - JavaScript + - NeedsTranslation + - Reference + - String + - TopicStub +translation_of: Web/JavaScript/Reference/Global_Objects/String +--- +
{{JSRef}}
+ +

The String global object is a constructor for strings, or a sequence of characters.

+ +

Syntax

+ +

String literals take the forms:

+ +
'string text'
+"string text"
+"中文 español English हिन्दी العربية português বাংলা русский 日本語 ਪੰਜਾਬੀ 한국어 தமிழ்"
+ +

Strings can also be created using the String global object directly:

+ +
String(thing)
+
+ +

Parameters

+ +
+
thing
+
Anything to be converted to a string.
+
+ +

Template strings

+ +

Since ECMAScript 2015, string literals can also be so-called Template strings:

+ +
`hello world`
+`hello!
+ world!`
+`hello ${who}`
+escape `<a>${who}</a>`
+ +
+
+ +

Escape notation

+ +

Beside regular, printable characters, special characters can be encoded using escape notation:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CodeOutput
\0the NULL character
\'single quote
\"double quote
\\backslash
\nnew line
\rcarriage return
\vvertical tab
\ttab
\bbackspace
\fform feed
\uXXXXunicode codepoint
\u{X} ... \u{XXXXXX}unicode codepoint {{experimental_inline}}
\xXXthe Latin-1 character
+ +

NOTE: Unlike some other languages, JavaScript makes no distinction between single-quoted strings and double-quoted strings, therefore, the escape sequences above work in strings created with either single or double quotes.

+ +
+
+ +

Long literal strings

+ +

Sometimes, your code will include strings which are very long. Rather than having lines that go on endlessly, or wrap at the whim of your editor, you may wish to specifically break the string into multiple lines in the source code without affecting the actual string contents. There are two ways you can do this.

+ +

You can use the + operator to append multiple strings together, like this:

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

Or you can use the backslash character ("\") at the end of each line to indicate that the string will continue on the next line. Make sure there is no space or any other character after the backslash (except for a line break), or as an indent; otherwise it will not work. That form looks like this:

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

Both of these result in identical strings being created.

+ +

Description

+ +

Strings are useful for holding data that can be represented in text form. Some of the most-used operations on strings are to check their {{jsxref("String.length", "length")}}, to build and concatenate them using the + and += string operators, checking for the existence or location of substrings with the {{jsxref("String.prototype.indexOf()", "indexOf()")}} method, or extracting substrings with the {{jsxref("String.prototype.substring()", "substring()")}} method.

+ +

Character access

+ +

There are two ways to access an individual character in a string. The first is the {{jsxref("String.prototype.charAt()", "charAt()")}} method:

+ +
return 'cat'.charAt(1); // returns "a"
+
+ +

The other way (introduced in ECMAScript 5) is to treat the string as an array-like object, where individual characters correspond to a numerical index:

+ +
return 'cat'[1]; // returns "a"
+
+ +

For character access using bracket notation, attempting to delete or assign a value to these properties will not succeed. The properties involved are neither writable nor configurable. (See {{jsxref("Object.defineProperty()")}} for more information.)

+ +

Comparing strings

+ +

C developers have the strcmp() function for comparing strings. In JavaScript, you just use the less-than and greater-than operators:

+ +
var a = 'a';
+var b = 'b';
+if (a < b) { // true
+  console.log(a + ' is less than ' + b);
+} else if (a > b) {
+  console.log(a + ' is greater than ' + b);
+} else {
+  console.log(a + ' and ' + b + ' are equal.');
+}
+
+ +

A similar result can be achieved using the {{jsxref("String.prototype.localeCompare()", "localeCompare()")}} method inherited by String instances.

+ +

Distinction between string primitives and String objects

+ +

Note that JavaScript distinguishes between String objects and primitive string values. (The same is true of {{jsxref("Boolean")}} and {{jsxref("Global_Objects/Number", "Numbers")}}.)

+ +

String literals (denoted by double or single quotes) and strings returned from String calls in a non-constructor context (i.e., without using the {{jsxref("Operators/new", "new")}} keyword) are primitive strings. JavaScript automatically converts primitives to String objects, so that it's possible to use String object methods for primitive strings. In contexts where a method is to be invoked on a primitive string or a property lookup occurs, JavaScript will automatically wrap the string primitive and call the method or perform the property lookup.

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

String primitives and String objects also give different results when using {{jsxref("Global_Objects/eval", "eval()")}}. Primitives passed to eval are treated as source code; String objects are treated as all other objects are, by returning the object. For example:

+ +
var s1 = '2 + 2';             // creates a string primitive
+var s2 = new String('2 + 2'); // creates a String object
+console.log(eval(s1));        // returns the number 4
+console.log(eval(s2));        // returns the string "2 + 2"
+
+ +

For these reasons, code may break when it encounters String objects when it expects a primitive string instead, although generally authors need not worry about the distinction.

+ +

A String object can always be converted to its primitive counterpart with the {{jsxref("String.prototype.valueOf()", "valueOf()")}} method.

+ +
console.log(eval(s2.valueOf())); // returns the number 4
+
+ +
Note: For another possible approach to strings in JavaScript, please read the article about StringView — a C-like representation of strings based on typed arrays.
+ +

Properties

+ +
+
{{jsxref("String.prototype")}}
+
Allows the addition of properties to a String object.
+
+ +

Methods

+ +
+
{{jsxref("String.fromCharCode()")}}
+
Returns a string created by using the specified sequence of Unicode values.
+
{{jsxref("String.fromCodePoint()")}} {{experimental_inline}}
+
Returns a string created by using the specified sequence of code points.
+
{{jsxref("String.raw()")}} {{experimental_inline}}
+
Returns a string created from a raw template string.
+
+ +

String generic methods

+ +
+

String generics are non-standard, deprecated and will get removed near future. Note that you can not rely on them cross-browser without using the shim that is provided below.

+
+ +

The String instance methods are also available in Firefox as of JavaScript 1.6 (not part of the ECMAScript standard) on the String object for applying String methods to any object:

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

{{jsxref("Global_Objects/Array", "Generics", "#Array_generic_methods", 1)}} are also available on {{jsxref("Array")}} methods.

+ +

The following is a shim to provide support to non-supporting browsers:

+ +
/*globals define*/
+// Assumes all supplied String instance methods already present
+// (one may use shims for these if not available)
+(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(String).filter(function(methodName) {
+    //   return typeof String[methodName] === 'function';
+    // });
+    methods = [
+      'quote', 'substring', 'toLowerCase', 'toUpperCase', 'charAt',
+      'charCodeAt', 'indexOf', 'lastIndexOf', 'startsWith', 'endsWith',
+      'trim', 'trimLeft', 'trimRight', 'toLocaleLowerCase',
+      'toLocaleUpperCase', 'localeCompare', 'match', 'search',
+      'replace', 'split', 'substr', 'concat', 'slice'
+    ],
+    methodCount = methods.length,
+    assignStringGeneric = function(methodName) {
+      var method = String.prototype[methodName];
+      String[methodName] = function(arg1) {
+        return method.apply(arg1, Array.prototype.slice.call(arguments, 1));
+      };
+    };
+
+  for (i = 0; i < methodCount; i++) {
+    assignStringGeneric(methods[i]);
+  }
+}());
+
+ +

String instances

+ +

Properties

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

Methods

+ +

Methods unrelated to HTML

+ +
{{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')}}
+ +

Examples

+ +

String conversion

+ +

It's possible to use String as a "safer" {{jsxref("String.prototype.toString()", "toString()")}} alternative, as although it still normally calls the underlying toString(), it also works for {{jsxref("null")}} and {{jsxref("undefined")}}. For example:

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

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition.
{{SpecName('ES5.1', '#sec-15.5', 'String')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-string-objects', 'String')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-string-objects', 'String')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("1")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
\u{XXXXXX}{{CompatUnknown}}{{CompatGeckoDesktop("40")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
\u{XXXXXX}{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("40")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

See also

+ + diff --git a/files/nl/web/javascript/reference/global_objects/string/indexof/index.html b/files/nl/web/javascript/reference/global_objects/string/indexof/index.html new file mode 100644 index 0000000000..efb0b0937f --- /dev/null +++ b/files/nl/web/javascript/reference/global_objects/string/indexof/index.html @@ -0,0 +1,200 @@ +--- +title: String.prototype.indexOf() +slug: Web/JavaScript/Reference/Global_Objects/String/indexOf +tags: + - JavaScript + - Method + - Prototype + - Reference + - String +translation_of: Web/JavaScript/Reference/Global_Objects/String/indexOf +--- +
{{JSRef}}
+ +

De indexOf() methode geeft de positie van het eerste voorval van searchValue binnen het {{jsxref("String")}} object waarop het wordt aangeroepen, waarbij begonnen wordt met zoeken vanaf fromIndex. Geeft -1 terug als geen voorvallen van searchValue gevonden worden.

+ +

Syntaxis

+ +
str.indexOf(searchValue[, fromIndex])
+ +

Parameters

+ +
+
searchValue
+
De string om naar te zoeken.
+
fromIndex {{optional_inline}}
+
De index vanaf waar gezocht moet worden binnen de string. Dit kan elke integer zijn. De standaard waarde is 0, waardoor de hele string wordt doorzocht. Als fromIndex < 0 is wordt de hele string doorzocht. Als fromIndex >= str.length is wordt de string niet doorzocht en wordt -1 teruggegeven. (behalve als searchValue een lege string is, dan wordt str.length teruggegeven)
+
+ +

Return waarde

+ +

De index waarop de gespecificeerde waarde het eerst voorkomt in de string; -1 als die niet gevonden wordt.

+ +

Beschrijving

+ +

Karakters in een string zijn geïndexeerd van links naar rechts. De index van het eerste karakter is 0 en de index van het laatste karakter van een string genaamd stringName is stringName.length - 1.

+ +
'Blue Whale'.indexOf('Blue');     // geeft 0 terug
+'Blue Whale'.indexOf('Blute');    // geeft -1 terug
+'Blue Whale'.indexOf('Whale', 0); // geeft 5 terug
+'Blue Whale'.indexOf('Whale', 5); // geeft 5 terug
+'Blue Whale'.indexOf('', 9);      // geeft 9 terug
+'Blue Whale'.indexOf('', 10);     // geeft 10 terug
+'Blue Whale'.indexOf('', 11);     // geeft 11 terug
+
+ +

Hoofdlettergevoeligheid

+ +

De indexOf() methode is hoofdlettergevoelig. Het volgende voorbeeld geeft -1 terug:

+ +
'Blue Whale'.indexOf('blue'); // geeft -1 terug
+
+ +

Voorvallen controleren

+ +

Onthoudt dat '0' niet vertaalt naar true en '-1' niet vertaalt naar false. Hierdoor moet op de volgende manier gekeken worden of een string binnen een andere string zit:

+ +
'Blue Whale'.indexOf('Blue') !== -1; // true
+'Blue Whale'.indexOf('Bloe') !== -1; // false
+
+ +

Examples

+ +

indexOf() en lastIndexOf() gebruiken

+ +

Het volgende voorbeeld gebruikt indexOf() en {{jsxref("String.prototype.lastIndexOf()", "lastIndexOf()")}} om waardes binnen de string  "Brave new world" te vinden.

+ +
var anyString = 'Brave new world';
+
+console.log('De index van de eerste w vanaf het begin is ' + anyString.indexOf('w'));
+// logs 8
+console.log('De index van de eerste w vanaf het begin is ' + anyString.lastIndexOf('w'));
+// logs 10
+
+console.log('De index van "new" vanaf het begin is ' + anyString.indexOf('new'));
+// logs 6
+console.log('De index van "new" vanaf het eind is ' + anyString.lastIndexOf('new'));
+// logs 6
+
+ +

indexOf() en hoofdlettergevoeligheid

+ +

Het volgende voorbeeld legt twee string variabelen vast. Deze variabelen bevatten dezelfde string, behalve dat de tweede string hoofdletters bevat. De eerste {{domxref("console.log()")}} methode geeft 19 terug. Omdat de indexOf() methode hoofdlettergevoelig is, wordt de string "cheddar" niet gevonden in myCapString, dus de tweede console.log() methode geeft -1 terug.

+ +
var myString    = 'brie, pepper jack, cheddar';
+var myCapString = 'Brie, Pepper Jack, Cheddar';
+
+console.log('myString.indexOf("cheddar") geeft ' + myString.indexOf('cheddar'));
+// geeft 19
+console.log('myCapString.indexOf("cheddar") geeft ' + myCapString.indexOf('cheddar'));
+// geeft -1
+
+ +

indexOf() gebruiken om voorvallen van een letter in een string te tellen

+ +

In het volgende voorbeeld wordt in count de hoeveelheid voorvallen van e in de string str bijgehouden:

+ +
var str = 'To be, or not to be, that is the question.';
+var count = 0;
+var pos = str.indexOf('e');
+
+while (pos !== -1) {
+  count++;
+  pos = str.indexOf('e', pos + 1);
+}
+
+console.log(count); // geeft 4
+
+ +

Specificaties

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificatieStatusOpmerking
{{SpecName('ES1')}}{{Spec2('ES1')}}Eerste definitie.
{{SpecName('ES5.1', '#sec-15.5.4.7', 'String.prototype.indexOf')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-string.prototype.indexof', 'String.prototype.indexOf')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-string.prototype.indexof', 'String.prototype.indexOf')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibiliteit

+ +
{{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}}
+
+ +

Zie ook

+ + diff --git a/files/nl/web/javascript/reference/global_objects/string/startswith/index.html b/files/nl/web/javascript/reference/global_objects/string/startswith/index.html new file mode 100644 index 0000000000..b183929746 --- /dev/null +++ b/files/nl/web/javascript/reference/global_objects/string/startswith/index.html @@ -0,0 +1,96 @@ +--- +title: String.prototype.startsWith() +slug: Web/JavaScript/Reference/Global_Objects/String/startsWith +tags: + - Begin + - JavaScript + - Méthode + - String +translation_of: Web/JavaScript/Reference/Global_Objects/String/startsWith +--- +
{{JSRef}}
+ +

De startsWith() methode bepaalt of een string begint met de karakters van een bepaalde string. Deze geeft true of false terug waar nodig.

+ +

Syntax

+ +
str.startsWith(zoekString[, positie])
+ +

Parameters

+ +
+
zoekString
+
De karakters om te zoeken aan het begin van de string.
+
positie{{optional_inline}}
+
De positie in de string waar je start met zoeken naar zoekString; start standaard op 0.
+
+ +

Resultaat

+ +

true als de karakters teruggevonden worden aan het begin van de string, anders false.

+ +

Beschrijving

+ +

Deze methde laat je nagaan of een string begint met een andere string. Dit is hoofdletter gevoelig

+ +

Voorbeelden

+ +

Gebruik startsWith()

+ +
//startswith
+var str = 'Te nemen of te laten.';
+
+console.log(str.startsWith('Te nemen'));         // true
+console.log(str.startsWith('te laten'));     // false
+console.log(str.startsWith('te laten', 12)); // true
+
+ +

Polyfill

+ +

Deze methode is toegevoegd aan de ECMAScript 2015 specificaties en is misschien nog niet beschikbaar in alle JavaScript implementaties. Je kan wel Polyfill  String.prototype.startsWith() alsvolgt gebruiken

+ +
if (!String.prototype.startsWith) {
+	String.prototype.startsWith = function(search, pos) {
+		return this.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search;
+	};
+}
+
+ +

Een meer degelijke en geoptimaliseerde Polyfill is beschikbaar op GitHub door Mathias Bynens.

+ +

Specificaties

+ + + + + + + + + + + + + + + + + + + +
SpecificatieStatusCommentaar
{{SpecName('ES2015', '#sec-string.prototype.startswith', 'String.prototype.startsWith')}}{{Spec2('ES2015')}}Eerste definitie.
{{SpecName('ESDraft', '#sec-string.prototype.startswith', 'String.prototype.startsWith')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibiliteit

+ + + +

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

+ +

Meer lezen

+ + diff --git a/files/nl/web/javascript/reference/global_objects/string/tolowercase/index.html b/files/nl/web/javascript/reference/global_objects/string/tolowercase/index.html new file mode 100644 index 0000000000..4716e5afa5 --- /dev/null +++ b/files/nl/web/javascript/reference/global_objects/string/tolowercase/index.html @@ -0,0 +1,125 @@ +--- +title: String.prototype.toLowerCase() +slug: Web/JavaScript/Reference/Global_Objects/String/toLowerCase +tags: + - JavaScript + - Method + - Prototype + - Reference + - String +translation_of: Web/JavaScript/Reference/Global_Objects/String/toLowerCase +--- +
{{JSRef}}
+ +

De toLowerCase() methode geeft een string terug waarbij de meegegeven string naar kleine letters is geconverteerd.

+ +

Syntax

+ +
str.toLowerCase()
+ +

Returnwaarde

+ +

Een nieuwe string waarbij de meegegeven string naar kleine letters is geconverteerd.

+ +

Beschrijving

+ +

De toLowerCase() methode geeft een string terug waarbij de meegegeven string naar kleine letters is geconverteerd. toLowerCase() past de waarde van de meegegeven string str niet aan.

+ +

Examples

+ +

Gebruik van toLowerCase()

+ +
console.log('ALFABET'.toLowerCase()); // 'alfabet'
+
+ +

Specificaties

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificatieStatusOpmerking
{{SpecName('ES1')}}{{Spec2('ES1')}}Initiële definitie. Geïmplementeerd in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.5.4.16', 'String.prototype.toLowerCase')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-string.prototype.tolowercase', 'String.prototype.toLowerCase')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-string.prototype.tolowercase', 'String.prototype.toLowerCase')}}{{Spec2('ESDraft')}} 
+ +

Browsercompatibiliteit

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

Zie ook

+ + diff --git a/files/nl/web/javascript/reference/global_objects/string/touppercase/index.html b/files/nl/web/javascript/reference/global_objects/string/touppercase/index.html new file mode 100644 index 0000000000..32393e3c86 --- /dev/null +++ b/files/nl/web/javascript/reference/global_objects/string/touppercase/index.html @@ -0,0 +1,125 @@ +--- +title: String.prototype.toUpperCase() +slug: Web/JavaScript/Reference/Global_Objects/String/toUpperCase +tags: + - JavaScript + - Method + - Prototype + - Reference + - String +translation_of: Web/JavaScript/Reference/Global_Objects/String/toUpperCase +--- +
{{JSRef}}
+ +

De toUpperCase() methode geeft een string terug waarbij de meegegeven string naar hoofdletters is geconverteerd.

+ +

Syntax

+ +
str.toUpperCase()
+ +

Returnwaarde

+ +

Een nieuwe string waarbij de meegegeven string naar hoofdletters is geconverteerd.

+ +

Beschrijving

+ +

De toUpperCase() methode geeft een string terug waarbij de meegegeven string naar hoofdletters is geconverteerd.. toUpperCase() past de waarde van de meegegeven string niet aan.

+ +

Voorbeelden

+ +

Gebruik van toUpperCase()

+ +
console.log('alfabet'.toUpperCase()); // 'ALFABET'
+
+ +

Specificaties

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificatieStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initiële definitie. Geïmplementeerd in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.5.4.18', 'String.prototype.toUpperCase')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-string.prototype.touppercase', 'String.prototype.toUpperCase')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-string.prototype.touppercase', 'String.prototype.toUpperCase')}}{{Spec2('ESDraft')}} 
+ +

Browsercompatibiliteit

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

Zie ook

+ + diff --git a/files/nl/web/javascript/reference/global_objects/string/trim/index.html b/files/nl/web/javascript/reference/global_objects/string/trim/index.html new file mode 100644 index 0000000000..c595279b0d --- /dev/null +++ b/files/nl/web/javascript/reference/global_objects/string/trim/index.html @@ -0,0 +1,139 @@ +--- +title: String.prototype.trim() +slug: Web/JavaScript/Reference/Global_Objects/String/Trim +tags: + - ECMAScript6 + - JavaScript + - Method + - Prototype + - Reference + - String +translation_of: Web/JavaScript/Reference/Global_Objects/String/Trim +--- +
{{JSRef}}
+ +

De trim() methode verwijdert witruimte aan het begin en einde van een string. Witruimte betreft in deze context alle whitespace karakters (spatie, tab, no-break spatie, etc.) en alle regeleindekarakters (LF, CR, etc.).

+ +

Syntax

+ +
str.trim()
+ +

Returnwaarde

+ +

Een nieuwe string waarbij de meegegeven string geen witruimte aan beide kanten meer heeft.

+ +

Beschrijving

+ +

De trim() methode geeft een string terug waarvan aan het begin en einde de witruimte is afgestript. trim() past de waarde van de string zelf niet aan.

+ +

Voorbeelden

+ +

Het gebruik van trim()

+ +

Het volgende voorbeeld toont de string 'foo':

+ +
var orig = '   foo  ';
+console.log(orig.trim()); // 'foo'
+
+// Ander voorbeeld .trim() voor het verwijderen van witruimte aan een kant.
+
+var orig = 'foo    ';
+console.log(orig.trim()); // 'foo'
+
+ +

Polyfill

+ +

Roep de volgende code aan voor het aanroepen van andere code, om trim() beschikbaar te maken als deze nog niet oorspronkelijk ondersteund werd.

+ +
if (!String.prototype.trim) {
+  String.prototype.trim = function () {
+    return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
+  };
+}
+
+ +

Specificaties

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificatieStatusOpmerking
{{SpecName('ES5.1', '#sec-15.5.4.20', 'String.prototype.trim')}}{{Spec2('ES5.1')}}Initiële definitie. Geïmplementeerd in JavaScript 1.8.1.
{{SpecName('ES6', '#sec-string.prototype.trim', 'String.prototype.trim')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-string.prototype.trim', 'String.prototype.trim')}}{{Spec2('ESDraft')}}
+ +

Browsercompatibiliteit

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basisondersteuning{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.9.1")}}{{CompatIE("9")}}{{CompatOpera("10.5")}}{{CompatSafari("5")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basisondersteuning{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Zie ook

+ + diff --git a/files/nl/web/javascript/reference/global_objects/symbool/index.html b/files/nl/web/javascript/reference/global_objects/symbool/index.html new file mode 100644 index 0000000000..f0777451c8 --- /dev/null +++ b/files/nl/web/javascript/reference/global_objects/symbool/index.html @@ -0,0 +1,205 @@ +--- +title: Symbool +slug: Web/JavaScript/Reference/Global_Objects/Symbool +tags: + - ECMAScript 2015 + - JavaScript + - Klasse + - Symbool +translation_of: Web/JavaScript/Reference/Global_Objects/Symbol +--- +
{{JSRef}}
+ +

Het gegevenstype symbool is een primitief gegevenstype. De Symbol() functie geeft een waarde terug (returns a value) van het type symbool, heeft statische eigenschappen die verscheidene leden van ingebouwde objecten blootstelt, heeft statische methoden die het globale symbolregister blootstellen en vertegenwoordigd een ingebouwde objectklasse. Maar is onvolledig als een constructor, omdat het niet de "new Symbol()" syntaxis ondersteund.

+ +

Elke waarde teruggekregen van Symbol() is uniek. Zo'n teruggekregen waarde kan, bijvoorbeeld, gebruikt worden als identificatiemiddel voor objecteigenschappen; het primaire doel van dit gegevenstype. Hoewel er andere use-cases zijn, zoals het beschikbaar maken van ondoorzichtige gegevenstypen of als algemeen uniek identificatiemiddel. Meer uitleg over het doel en gebruik van het symbool is te vinden in de woordenlijst.

+ +

Beschrijving

+ +

Om een nieuw primitief symbool te creëren, schrijf je Symbol() met een optionele String als beschrijving:

+ +
let sym1 = Symbol()
+let sym2 = Symbol('foo')
+let sym3 = Symbol('foo')
+
+ +

De bovenstaande code creëert drie nieuwe symbolen. Let er op dat Symbol("foo") niet de string "foo" omzet naar een symbool maar dat het telkens een nieuw uniek symbool creëert:

+ +
Symbol('foo') === Symbol('foo')  // false
+
+ +

De volgende syntaxis met de {{jsxref("Operators/new", "new")}} operator zal een {{jsxref("TypeError")}}: afwerpen:

+ +
let sym = new Symbol()  // TypeError
+
+ +

Dit behoed auteurs ervoor om nadrukkelijk een Symbol wrapper-object te creëren in plaats van een nieuwe symboolwaarde. Terwijl normaal gesproken primitieve gegevenstypen wel gemaakt kunnen worden met een wrapper-object. (Zoals: new Boolean, new String en new Number).

+ +

Als je echt een Symbol wrapper-object wilt maken, kun je dit doen met de Object() functie:

+ +
let sym = Symbol('foo')
+typeof sym      // "symbol"
+let symObj = Object(sym)
+typeof symObj   // "object"
+
+ +

Gedeelde symbolen in het globale symboolregister

+ +

De bovenstaande syntaxis, die gebruik maakt van de Symbol() functie, creëert alleen niet een globaal symbool dat te gebruiken is door je gehele codebase. Om symbolen te creëren die door al je bestanden en zelfs door je realms (met elk hun eigen globale scope) te gebruiken zijn; gebruik je de methoden {{jsxref("Symbol.for()")}} en {{jsxref("Symbol.keyFor()")}}. Om, respectievelijksymbolen in het globale symbolenregister aan te maken en terug te krijgen.

+ +

Symbooleigenschappen vinden in objecten

+ +

De methode {{jsxref("Object.getOwnPropertySymbols()")}} geeft een array met symbolen terug en laat je symbooleigenschappen vinden in een opgegeven object. Let er op dat elk object geïnitialiseerd wordt zonder eigen symbooleigenschappen, dus deze array zal leeg zijn tenzij je een symbool als eigenschap hebt gegeven aan een object. 

+ +

Constructor

+ +
+
Symbol()
+
De  Symbol() constructor geeft een waarde terug van het type symbol, maar is incompleet als een constructor omdat het niet de "new Symbol()" syntaxis ondersteund.
+
+ +

Static properties

+ +
+
{{jsxref("Symbol.asyncIterator")}}
+
A method that returns the default AsyncIterator for an object. Used by for await...of.
+
{{jsxref("Symbol.hasInstance")}}
+
A method determining if a constructor object recognizes an object as its instance. Used by {{jsxref("Operators/instanceof", "instanceof")}}.
+
{{jsxref("Symbol.isConcatSpreadable")}}
+
A Boolean value indicating if an object should be flattened to its array elements. Used by {{jsxref("Array.prototype.concat()")}}.
+
{{jsxref("Symbol.iterator")}}
+
A method returning the default iterator for an object. Used by for...of.
+
{{jsxref("Symbol.match")}}
+
A method that matches against a string, also used to determine if an object may be used as a regular expression. Used by {{jsxref("String.prototype.match()")}}.
+
{{jsxref("Symbol.matchAll")}}
+
A method that returns an iterator, that yields matches of the regular expression against a string. Used by {{jsxref("String.prototype.matchAll()")}}.
+
{{jsxref("Symbol.replace")}}
+
A method that replaces matched substrings of a string. Used by {{jsxref("String.prototype.replace()")}}.
+
{{jsxref("Symbol.search")}}
+
A method that returns the index within a string that matches the regular expression. Used by {{jsxref("String.prototype.search()")}}.
+
{{jsxref("Symbol.split")}}
+
A method that splits a string at the indices that match a regular expression. Used by {{jsxref("String.prototype.split()")}}.
+
{{jsxref("Symbol.species")}}
+
A constructor function that is used to create derived objects.
+
{{jsxref("Symbol.toPrimitive")}}
+
A method converting an object to a primitive value.
+
{{jsxref("Symbol.toStringTag")}}
+
A string value used for the default description of an object. Used by {{jsxref("Object.prototype.toString()")}}.
+
{{jsxref("Symbol.unscopables")}}
+
An object value of whose own and inherited property names are excluded from the with environment bindings of the associated object.
+
+ +

Static methods

+ +
+
{{jsxref("Symbol.for()", "Symbol.for(key)")}}
+
Searches for existing symbols with the given key and returns it if found. Otherwise a new symbol gets created in the global symbol registry with key.
+
{{jsxref("Symbol.keyFor", "Symbol.keyFor(sym)")}}
+
Retrieves a shared symbol key from the global symbol registry for the given symbol.
+
+ +

Instance properties

+ +
+
{{jsxref("Symbol.prototype.description")}}
+
A read-only string containing the description of the symbol.
+
+ +

Instance methods

+ +
+
{{jsxref("Symbol.prototype.toSource()")}}
+
Returns a string containing the source of the {{jsxref("Global_Objects/Symbol", "Symbol")}} object. Overrides the {{jsxref("Object.prototype.toSource()")}} method.
+
{{jsxref("Symbol.prototype.toString()")}}
+
Returns a string containing the description of the Symbol. Overrides the {{jsxref("Object.prototype.toString()")}} method.
+
{{jsxref("Symbol.prototype.valueOf()")}}
+
Returns the primitive value of the {{jsxref("Symbol")}} object. Overrides the {{jsxref("Object.prototype.valueOf()")}} method.
+
{{jsxref("Symbol.prototype.@@toPrimitive()", "Symbol.prototype[@@toPrimitive]")}}
+
Returns the primitive value of the {{jsxref("Symbol")}} object.
+
+ +

Examples

+ +

Using the typeof operator with symbols

+ +

The {{jsxref("Operators/typeof", "typeof")}} operator can help you to identify symbols.

+ +
typeof Symbol() === 'symbol'
+typeof Symbol('foo') === 'symbol'
+typeof Symbol.iterator === 'symbol'
+
+ +

Symbol type conversions

+ +

Some things to note when working with type conversion of symbols.

+ + + +

Symbols and for...in iteration

+ +

Symbols are not enumerable in for...in iterations. In addition, {{jsxref("Object.getOwnPropertyNames()")}} will not return symbol object properties, however, you can use {{jsxref("Object.getOwnPropertySymbols()")}} to get these.

+ +
let obj = {}
+
+obj[Symbol('a')] = 'a'
+obj[Symbol.for('b')] = 'b'
+obj['c'] = 'c'
+obj.d = 'd'
+
+for (let i in obj) {
+   console.log(i)  // logs "c" and "d"
+}
+ +

Symbols and JSON.stringify()

+ +

Symbol-keyed properties will be completely ignored when using JSON.stringify():

+ +
JSON.stringify({[Symbol('foo')]: 'foo'})
+// '{}'
+
+ +

For more details, see {{jsxref("JSON.stringify()")}}.

+ +

Symbol wrapper objects as property keys

+ +

When a Symbol wrapper object is used as a property key, this object will be coerced to its wrapped symbol:

+ +
let sym = Symbol('foo')
+let obj = {[sym]: 1}
+obj[sym]             // 1
+obj[Object(sym)]     // still 1
+
+ +

Specifications

+ + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-symbol-objects', 'Symbol')}}
+ +

Browser compatibility

+ + + +

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

+ +

See also

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

This part of the JavaScript section on MDN serves as a repository of facts about the JavaScript language. Read more about this reference.

+ +

Global Objects

+ +

This chapter documents all the JavaScript standard built-in objects, along with their methods and properties.

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

Statements

+ +

This chapter documents all the JavaScript statements and declarations.

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

Expressions and operators

+ +

This chapter documents all the JavaScript expressions and operators.

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

Functions

+ +

This chapter documents how to work with JavaScript functions to develop your applications.

+ + + +

Additional reference pages

+ + diff --git a/files/nl/web/javascript/reference/klasses/index.html b/files/nl/web/javascript/reference/klasses/index.html new file mode 100644 index 0000000000..ca5210371c --- /dev/null +++ b/files/nl/web/javascript/reference/klasses/index.html @@ -0,0 +1,252 @@ +--- +title: Klassen +slug: Web/JavaScript/Reference/Klasses +translation_of: Web/JavaScript/Reference/Classes +--- +
{{JsSidebar("Classes")}}
+ +

JavaScript classes zijn nieuw in ECMAScript 6. De class syntax is geen object-oriented inheritance model in JavaScript. JavaScript classes brengen een veel eenvoudigere en duidelijkere syntax voor het creëren van objecten.

+ +

Classes definiëren

+ +

Classes zijn eigenlijk functions, net zoals je function expressions en function declarations kan definiëren, de class syntax heeft twee componenten: class expressies en class declaraties.

+ +

Class declaraties

+ +

Eén manier om een class te definiëren is door gebruik te maken van class declaration. Om een klasse te declareren, gebruik je het class keyword gevolgd door de naam van de class. ("Polygon" hier).

+ +
class Polygon {
+  constructor(height, width) {
+    this.height = height;
+    this.width = width;
+  }
+}
+ +

Hoisting

+ +

Een belangrijk verschil tussen function declarations en class declarations is dat function declarations {{Glossary("Hoisting", "hoisted")}} zijn en class declarations niet. Je moet eerst je klasse declareren voor je het kan gebruiken, anders krijg je een {{jsxref("ReferenceError")}}:

+ +
var p = new Polygon(); // ReferenceError
+
+class Polygon {}
+
+ +

Class expressions

+ +

Een class expression is een andere manier om een class te definiëren. Class expressions kunnen named of unnamed zijn. De naam gegeven aan een named class expression is local aan de body van de class.

+ +
// unnamed
+var Polygon = class {
+  constructor(height, width) {
+    this.height = height;
+    this.width = width;
+  }
+};
+
+// named
+var Polygon = class Polygon {
+  constructor(height, width) {
+    this.height = height;
+    this.width = width;
+  }
+};
+
+ +

Class body en method definitions

+ +

De body van een class is het stuk tussen de curly brackets {}. Hier kan je class members definiëren, zoals methodes of constructors.

+ +

Strict mode

+ +

De bodies van class declarations en class expressions worden uitgevoerd in strict mode. Constructor, static en prototype methods, getter en setter functions worden bijvoorbeeld uitgevoerd in strict mode.

+ +

Constructor

+ +

De constructor methode is een speciale methode voor het creëren en initializeren van een object voor de klasse. Er kan maar één speciale methode zijn met de naam "constructor" in een klasse. Een {{jsxref("SyntaxError")}} wordt gegooid indien de klasse meerdere constructor methodes heeft.

+ +

Een constructor kan gebruik maken van het super keyword om de constructor van de parent class op te roepen.

+ +

Prototype methods

+ +

Zie ook method definitions.

+ +
class Polygon {
+  constructor(height, width) {
+    this.height = height;
+    this.width = width;
+  }
+
+  get area() {
+    return this.calcArea()
+  }
+
+  calcArea() {
+    return this.height * this.width;
+  }
+}
+ +

Static methods

+ +

Het static keyword beschrijft een statische methode voor een klasse. Statische methodes kunnen worden opgeroepen zonder dat er een instantie gemaakt is van de klasse en kunnen ook niet opgeroepen worden wanneer er een instantie van gemaakt is. Statische methodes zijn dikwijls gebruikt als utility functions voor een applicatie.

+ +
class Point {
+    constructor(x, y) {
+        this.x = x;
+        this.y = y;
+    }
+
+    static distance(a, b) {
+        const dx = a.x - b.x;
+        const dy = a.y - b.y;
+
+        return Math.sqrt(dx*dx + dy*dy);
+    }
+}
+
+const p1 = new Point(5, 5);
+const p2 = new Point(10, 10);
+
+console.log(Point.distance(p1, p2));
+ +

Sub classing met extends

+ +

Het extends keyword wordt gebruikt in class declarations of class expressions om een klasse aan te maken als kind van een andere klasse.

+ +
class Animal {
+  constructor(name) {
+    this.name = name;
+  }
+
+  speak() {
+    console.log(this.name + ' makes a noise.');
+  }
+}
+
+class Dog extends Animal {
+  speak() {
+    console.log(this.name + ' barks.');
+  }
+}
+
+ +

Sub classing built-in objects

+ +

TBD

+ +

Super class calls with super

+ +

Het super keyword wordt gebruikt om een methode op te roepen in de parent klasse van het object.

+ +
class Cat {
+  constructor(name) {
+    this.name = name;
+  }
+
+  speak() {
+    console.log(this.name + ' makes a noise.');
+  }
+}
+
+class Lion extends Cat {
+  speak() {
+    super.speak();
+    console.log(this.name + ' roars.');
+  }
+}
+
+ +

ES5 inheritance syntax en ES6 classes syntax vergeleken

+ +

TBD

+ +

Voorbeelden

+ +

TBD

+ +

Specificaties

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES6', '#sec-class-definitions', 'Class definitions')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-class-definitions', 'Class definitions')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibiliteit

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)MS EdgeInternet ExplorerOperaSafari
Basic support{{CompatChrome(42.0)}}[1]4513{{CompatNo}}{{CompatNo}}{{CompatSafari(9.0)}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}45{{CompatUnknown}}{{CompatUnknown}}9{{CompatChrome(42.0)}}[1]
+
+ +

[1] Requires strict mode. Non-strict mode support is behind the flag Enable Experimental JavaScript, disabled by default.

+ +

Zie ook

+ + diff --git a/files/nl/web/javascript/reference/operatoren/index.html b/files/nl/web/javascript/reference/operatoren/index.html new file mode 100644 index 0000000000..fc499002b4 --- /dev/null +++ b/files/nl/web/javascript/reference/operatoren/index.html @@ -0,0 +1,288 @@ +--- +title: Expressies and operators +slug: Web/JavaScript/Reference/Operatoren +translation_of: Web/JavaScript/Reference/Operators +--- +
{{jsSidebar("Operators")}}
+ +

Deze documentatie bevat informatie over JavaScript operators.

+ +

Expressies en operators per categorie

+ +

Voor alfabetische lijst, zie sidebar.

+ +

Primaire expressies

+ +

Trefwoorden en algmene expressies in JavaScript.

+ +
+
{{jsxref("Operators/this", "this")}}
+
this verwijst naar de context van een functie.
+
{{jsxref("Operators/function", "function")}}
+
function geeft aan dat er een functie moet worden gemaakt
+
{{experimental_inline}} {{jsxref("Operators/class", "class")}}
+
class definieert een klasse.
+
{{experimental_inline}} {{jsxref("Operators/function*", "function*")}}
+
Het function* trefwoord definieert een generator functie expressie.
+
{{experimental_inline}} {{jsxref("Operators/yield", "yield")}}
+
Pauzeer en start een generator functie.
+
{{experimental_inline}} {{jsxref("Operators/yield*", "yield*")}}
+
Doorgegeven aan een andere generator functie.
+
{{jsxref("Global_Objects/Array", "[]")}}
+
Definieert een lijst met data.
+
{{jsxref("Operators/Object_initializer", "{}")}}
+
Definieert een object.
+
{{jsxref("Global_Objects/RegExp", "/ab+c/i")}}
+
Reguliere expressie.
+
{{experimental_inline}} {{jsxref("Operators/Array_comprehensions", "[for (x of y) x]")}}
+
Datalijst omvang.
+
{{experimental_inline}} {{jsxref("Operators/Generator_comprehensions", "(for (x of y) y)")}}
+
Generator omvang.
+
{{jsxref("Operators/Grouping", "( )")}}
+
Groep operator.
+
+ +

Left-hand-side expressies

+ +

Deze voeren een opdracht uit met een van de bovenstaande expressies.

+ +
+
{{jsxref("Operators/Property_accessors", "Property accessors", "", 1)}}
+
Haalt data uit een object op
+ (object.property en object["property"]).
+
{{jsxref("Operators/new", "new")}}
+
Maakt een nieuwe constructor.
+
{{experimental_inline}} new.target
+
In constructors, new.target verwijst naar het object dat werd aangeroepen door {{jsxref("Operators/new", "new")}}. 
+
{{experimental_inline}} {{jsxref("Operators/super", "super")}}
+
Het super keywoord verwijst naar de hoofdconstructor.
+
{{experimental_inline}} {{jsxref("Operators/Spread_operator", "...obj")}}
+
De spread operator stelt een expressie uit te breiden op plaatsen waar meerdere argumenten (voor de functies die opgeroepen worden) of meerdere elementen (voor Array literalen) zijn verplicht.
+
+ +

Optellen en Aftrekken

+ +

Voor optellen en aftrekken bij variabelen.

+ +
+
{{jsxref("Operators/Arithmetic_Operators", "A++", "#Increment")}}
+
Achtervoegsel optel operator.
+
{{jsxref("Operators/Arithmetic_Operators", "A--", "#Decrement")}}
+
Achtervoegsel aftrek operator.
+
{{jsxref("Operators/Arithmetic_Operators", "++A", "#Increment")}}
+
Voorvoegsel optel operator.
+
{{jsxref("Operators/Arithmetic_Operators", "--A", "#Decrement")}}
+
Voorvoegsel aftrek operator.
+
+ +

Unaire operatoren

+ +

Een unaire operatie is een operatie met slechts één operand.

+ +
+
{{jsxref("Operators/delete", "delete")}}
+
De delete operator verwijdert een object of item van een object.
+
{{jsxref("Operators/void", "void")}}
+
De void operator verwijdert de returnwaarde van een expressie.
+
{{jsxref("Operators/typeof", "typeof")}}
+
De typeof operator geeft het type van het object.
+
We zijn bezig met vertalen van het document, maar we zijn nog niet klaar.
+
+ +
+
{{jsxref("Operators/Arithmetic_Operators", "+", "#Unary_plus")}}
+
De unaire plus operator zet zijn operand om naar type Number
+
{{jsxref("Operators/Arithmetic_Operators", "-", "#Unary_negation")}}
+
De unaire negatie operator zet zijn operand om naar Number en zet hem dan om in haar tegendeel.
+
{{jsxref("Operators/Bitwise_Operators", "~", "#Bitwise_NOT")}}
+
Bitwise NOT operator.
+
{{jsxref("Operators/Logical_Operators", "!", "#Logical_NOT")}}
+
Logische NOT operator.
+
+ +

Rekenkundige operators

+ +

Rekenkundige operators accepteren numerieke waarden (letterlijke waarden of variablen) als hun operand en retourneren een enkele numerieke waarde.

+ +
+
{{jsxref("Operators/Arithmetic_Operators", "+", "#Addition")}}
+
Additie operator.
+
{{jsxref("Operators/Arithmetic_Operators", "-", "#Subtraction")}}
+
Subtractie operator.
+
{{jsxref("Operators/Arithmetic_Operators", "/", "#Division")}}
+
Divisie operator.
+
{{jsxref("Operators/Arithmetic_Operators", "*", "#Multiplication")}}
+
Multiplicatie operator.
+
{{jsxref("Operators/Arithmetic_Operators", "%", "#Remainder")}}
+
Rest operator.
+
+ +
+
{{experimental_inline}} {{jsxref("Operators/Arithmetic_Operators", "**", "#Exponentiation")}}
+
Exponent operator.
+
+ +

Relationele operators

+ +

Een relationele operator vergelijkt zijn operanden en retourneert een Boolean gebaseerd op de uitkomst van de vergelijking.

+ +
+
{{jsxref("Operators/in", "in")}}
+
De in operator bepaalt of een object een zekere eigenschap heeft.
+
{{jsxref("Operators/instanceof", "instanceof")}}
+
De instanceof operator bepaalt of een variable een instantie is van een bepaald type object.
+
{{jsxref("Operators/Comparison_Operators", "<", "#Less_than_operator")}}
+
Minder dan operator.
+
{{jsxref("Operators/Comparison_Operators", ">", "#Greater_than_operator")}}
+
Groter dan operator.
+
{{jsxref("Operators/Comparison_Operators", "<=", "#Less_than_or_equal_operator")}}
+
Minder dan of gelijk aan operator.
+
{{jsxref("Operators/Comparison_Operators", ">=", "#Greater_than_or_equal_operator")}}
+
Groter dan of gelijk aan operator.
+
+ +

Gelijkheids operators

+ +

Het resultaat van het evalueren van een gelijkheids operator geeft altijd een Boolean gebaseerd op het resultaat van de vergelijking.

+ +
+
{{jsxref("Operators/Comparison_Operators", "==", "#Equality")}}
+
Gelijkheids operator.
+
{{jsxref("Operators/Comparison_Operators", "!=", "#Inequality")}}
+
Ongelijkheids operator.
+
{{jsxref("Operators/Comparison_Operators", "===", "#Identity")}}
+
Identiciteits operator.
+
{{jsxref("Operators/Comparison_Operators", "!==", "#Nonidentity")}}
+
Nonidenticiteits operator.
+
+ +

Bitwijs shift operators

+ +

Operaties die alle bits van de operand verschuiven.

+ +
+
{{jsxref("Operators/Bitwise_Operators", "<<", "#Left_shift")}}
+
Bitwijs linker shift operator.
+
{{jsxref("Operators/Bitwise_Operators", ">>", "#Right_shift")}}
+
Bitwijs rechter shift operator.
+
{{jsxref("Operators/Bitwise_Operators", ">>>", "#Unsigned_right_shift")}}
+
Bitwijs tekenloze rechter shift operator.
+
+ +

Binaire bitwijs operators

+ +

Bitwijs operatoren behandelen hun operand als een set van 32 bits en retourneren een standaard JavaScript numerieke waarde.

+ +
+
{{jsxref("Operators/Bitwise_Operators", "&", "#Bitwise_AND")}}
+
Bitwijs AND.
+
{{jsxref("Operators/Bitwise_Operators", "|", "#Bitwise_OR")}}
+
Bitwijs OR.
+
{{jsxref("Operators/Bitwise_Operators", "^", "#Bitwise_XOR")}}
+
Bitwijs XOR.
+
+ +

Binaire logische operators

+ +

Logische operatoren worden normaliter gebruikt met Booleans en retourneren ook een Boolean waarde.

+ +
+
{{jsxref("Operators/Logical_Operators", "&&", "#Logical_AND")}}
+
Logische AND.
+
{{jsxref("Operators/Logical_Operators", "||", "#Logical_OR")}}
+
Logische OR.
+
+ +

Conditionele (ternary) operator

+ +
+
{{jsxref("Operators/Conditional_Operator", "(condition ? ifTrue : ifFalse)")}}
+
+

The conditionele operator retourneert een of twee waarden gebaseerd op de waarde van de conditie.

+
+
+ +

Toekennings operators

+ +

Een toekennings operator kent een waarde toe aan zijn linker operand gebaseerd op de waarde van zijn rechter operand.

+ +
+
{{jsxref("Operators/Assignment_Operators", "=", "#Assignment")}}
+
Toekennings operator.
+
{{jsxref("Operators/Assignment_Operators", "*=", "#Multiplication_assignment")}}
+
Vermenigvuldigings toekenning.
+
{{jsxref("Operators/Assignment_Operators", "/=", "#Division_assignment")}}
+
Delings toekenning.
+
{{jsxref("Operators/Assignment_Operators", "%=", "#Remainder_assignment")}}
+
Rest toekenning.
+
{{jsxref("Operators/Assignment_Operators", "+=", "#Addition_assignment")}}
+
Additieve toekenning.
+
{{jsxref("Operators/Assignment_Operators", "-=", "#Subtraction_assignment")}}
+
Substractieve toekenning
+
{{jsxref("Operators/Assignment_Operators", "<<=", "#Left_shift_assignment")}}
+
Linker shift toekenning.
+
{{jsxref("Operators/Assignment_Operators", ">>=", "#Right_shift_assignment")}}
+
Rechter shift toekenning.
+
{{jsxref("Operators/Assignment_Operators", ">>>=", "#Unsigned_right_shift_assignment")}}
+
Tekenloze rechter shift toekenning.
+
{{jsxref("Operators/Assignment_Operators", "&=", "#Bitwise_AND_assignment")}}
+
Bitwijs AND toekenning.
+
{{jsxref("Operators/Assignment_Operators", "^=", "#Bitwise_XOR_assignment")}}
+
Bitwijs XOR toekenning.
+
{{jsxref("Operators/Assignment_Operators", "|=", "#Bitwise_OR_assignment")}}
+
Bitwijs OR toekenning.
+
{{experimental_inline}} {{jsxref("Operators/Destructuring_assignment", "[a, b] = [1, 2]")}}
+ {{experimental_inline}} {{jsxref("Operators/Destructuring_assignment", "{a, b} = {a:1, b:2}")}}
+
+

Ontbindings toekenningen maken het mogelijk eigenschappen van een array of object toe te kennen aan letterlijke arrays of objecten. 

+
+
+ +

Komma operator

+ +
+
{{jsxref("Operators/Comma_Operator", ",")}}
+
De komma operator maakt het mogelijk meerdere expressies te evalueren in een enkele statement en retourneert het resultaat van de laatste expressie.
+
+ +

Niet-standaard features

+ +
+
{{non-standard_inline}} {{jsxref("Operators/Legacy_generator_function", "Legacy generator function", "", 1)}}
+
Het function trefwoord kan worden gebruikt om een legacy generator functie te omschrijven binnen een expressie. Hiertoe moet de inhoud van de functie minstens 1  {{jsxref("Operators/yield", "yield")}} expressie bevatten.
+
{{non-standard_inline}} {{jsxref("Operators/Expression_closures", "Expression closures", "", 1)}}
+
De expressie sluitings  syntax is een mogelijkheid om een verkorte functie te schrijven.
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES6', '#sec-ecmascript-language-expressions', 'ECMAScript Language: Expressions')}}{{Spec2('ES6')}}New: Spread operator, destructuring assignment, super keyword, Array comprehensions, Generator comprehensions
{{SpecName('ES5.1', '#sec-11', 'Expressions')}}{{Spec2('ES5.1')}} 
{{SpecName('ES1', '#sec-11', 'Expressions')}}{{Spec2('ES1')}}Initial definition
+ +

See also

+ + diff --git a/files/nl/web/javascript/reference/operatoren/typeof/index.html b/files/nl/web/javascript/reference/operatoren/typeof/index.html new file mode 100644 index 0000000000..e86cf0b324 --- /dev/null +++ b/files/nl/web/javascript/reference/operatoren/typeof/index.html @@ -0,0 +1,244 @@ +--- +title: typeof +slug: Web/JavaScript/Reference/Operatoren/typeof +tags: + - JavaScript + - Operator + - Unair +translation_of: Web/JavaScript/Reference/Operators/typeof +--- +
{{jsSidebar("Operators")}}
+ +

De typeof-operator geeft een string terug die het type van de ongeëvalueerde operand weergeeft.

+ +

Syntaxis

+ +

De typeof-operator wordt gevolgd door zijn operand:

+ +
typeof operand
+ +

Parameters

+ +

operand is een uitdrukking die het object of de {{Glossary("Primitive", "primitief")}} voorstelt waarvan het type moet worden teruggegeven.

+ +

Beschrijving

+ +

De volgende tabel bevat de mogelijke waarden die typeof kan teruggeven. Voor meer informatie over types of primitieven, zie pagina datastructuren in Javascript.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
TypeResultaat
Undefined"undefined"
Null"object" (see below)
Boolean"boolean"
Number"number"
String"string"
Symbol (nieuw in ECMAScript 2015)"symbol"
Host object (voorzien door de JS omgeving)Implementatie-afhankelijk
Function object (implementeert [[Call]] in termen van ECMA-262)"function"
Elk ander object"object"
+ +

 

+ +

Voorbeelden

+ +
// Nummers
+typeof 37 === 'number';
+typeof 3.14 === 'number';
+typeof(42) === 'number';
+typeof Math.LN2 === 'number';
+typeof Infinity === 'number';
+typeof NaN === 'number'; // Ondanks dat het "Not-A-Number" is
+typeof Number(1) === 'number'; // maar gebruik deze manier nooit!
+
+
+// Strings
+typeof "" === 'string';
+typeof "bla" === 'string';
+typeof (typeof 1) === 'string'; // typeof geeft altijd een string terug
+typeof String("abc") === 'string'; // maar gebruik deze manier nooit!
+
+
+// Booleans
+typeof true === 'boolean';
+typeof false === 'boolean';
+typeof Boolean(true) === 'boolean'; // maar gebruik deze manier nooit!
+
+
+// Symbolen
+typeof Symbol() === 'symbol'
+typeof Symbol('foo') === 'symbol'
+typeof Symbol.iterator === 'symbol'
+
+
+// Ongedefinieerd
+typeof undefined === 'undefined';
+typeof declaredButUndefinedVariable === 'undefined';
+typeof undeclaredVariable === 'undefined';
+
+
+// Objecten
+typeof {a:1} === 'object';
+
+// gebruik Array.isArray of Object.prototype.toString.call
+// om het verschil aan te geven tussen normale objecten en
+// arrays (rijen).
+typeof [1, 2, 4] === 'object';
+
+typeof new Date() === 'object';
+
+
+// Het volgende is verwarrend. Niet gebruiken!
+typeof new Boolean(true) === 'object';
+typeof new Number(1) === 'object';
+typeof new String("abc") === 'object';
+
+
+// Functies
+typeof function(){} === 'function';
+typeof class C {} === 'function';
+typeof Math.sin === 'function';
+
+ +

null

+ +
// Dit geldt sinds het ontstaan van JavaScript
+typeof null === 'object';
+
+ +

In de oorspronkelijke implementatie van JavaScript werden JavaScript-waarden gerepresenteerd met een type-label en een waarde. Het type-label voor de meeste objecten was 0. null werd voorgesteld als de NULL-pointer (0x00 in de meeste platformen). Daarom had null het type-label 0, wat de foute typeof teruggeefwaarde verklaart. (referentie)

+ +

Een oplossing (via een opt-in) werd voorgesteld voor ECMAScript, maar die werd afgekeurd. Anders zou het er als volgt hebben uitgezien: typeof null === 'null'.

+ +

De new-operator gebruiken

+ +
// Alle constructorfuncties die worden geïnstantieerd met het
+// 'new'-sleutelwoord, zullen altijd typeof 'object' zijn.
+var str = new String('String');
+var num = new Number(100);
+
+typeof str; // Geeft 'object' terug
+typeof num; // Geeft 'object' terug
+
+// Maar er is een uitzondering in het geval van de functieconstructor van JavaScript.
+
+var func = new Function();
+
+typeof func; // Geeft 'function' terug
+
+ +

Reguliere uitdrukkingen

+ +

Aanroepbare reguliere uitdrukkingen waren een niet-standaard toevoeging in sommige browsers.

+ +
typeof /s/ === 'function'; // Chrome 1-12 Niet comform aan ECMAScript 5.1
+typeof /s/ === 'object';   // Firefox 5+  Conform aan ECMAScript 5.1
+
+ +

Temporal Dead Zone-fouten

+ +

Voor ECMAScript 2015 gaf typeof altijd gegarandeerd een string terug voor elke operand waarmee het was voorzien. Maar met de toevoeging van niet-gehoiste, blokgekaderde let en const ontstaat er een ReferenceError als typeof op let- en const-variabelen wordt gebruikt voordat ze zijn benoemd. Dit staat in contrast met onbenoemde variabelen, waarvoor typeof 'undefined' teruggeeft. Blokgekaderde variabelen zijn in een "temporal dead zone" vanaf het begin van het blok totdat de intialisatie is verwerkt, waarin een fout ontstaat als ze worden benaderd.

+ +
typeof onbenoemdeVariabele === 'undefined';
+typeof nieuweLetVariabele; let nieuweLetVariabele; // ReferenceError
+typeof nieuweConstVariabele; const nieuweConstVariabele = 'hallo'; // ReferenceError
+
+ +

Uitzonderingen

+ +

Alle huidige browsers onthullen een niet-standaard hostobject {{domxref("document.all")}} met type undefined.

+ +
typeof document.all === 'undefined';
+
+ +

Hoewel de specificatie aangepaste type-labels toestaat voor niet-standaard exotische objecten, vereist het dat die type-labels verschillen van de ingebouwde. Dat document.all een type-label undefined heeft moet worden geclassificeerd als een uitzonderlijke overtreding van de regels.

+ +

Specificaties

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificatieStatusOpmerking
{{SpecName('ESDraft', '#sec-typeof-operator', 'The typeof Operator')}}{{Spec2('ESDraft')}} 
{{SpecName('ES6', '#sec-typeof-operator', 'The typeof Operator')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-11.4.3', 'The typeof Operator')}}{{Spec2('ES5.1')}} 
{{SpecName('ES3', '#sec-11.4.3', 'The typeof Operator')}}{{Spec2('ES3')}} 
{{SpecName('ES1', '#sec-11.4.3', 'The typeof Operator')}}{{Spec2('ES1')}}Oorspronkelijke definitie. Geïmplementeerd in JavaScript 1.1.
+ +

Browsercompatibiliteit

+ + + +

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

+ +

IE-specifieke opmerkingen

+ +

In IE 6, 7, en 8 zijn een groot aantal host objecten objecten en geen functions. bijvoorbeeld:

+ +
typeof alert === 'object'
+ +

Zie ook

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

Het export statement wordt gebruikt bij het maken van JavaScript modules om functies, objecten of primitieve waarden te exporteren van de module zodat deze gebruikt kunnen worden door andere programmas met het {{jsxref("Statements/import", "import")}} statement.

+ +

Geëxporteerde modules worden altijd uitgevoerd in {{jsxref("Strict_mode","strict mode")}}, ongeacht of dat is aangegeven. Het export-statement kan niet gebruikt worden in ingevoegde scripts.

+ +
+

Deze functie is momenteel niet geïmplementeerd in Internet Explorer, Android webview en Samsung Internet. Het is wel geïmplementeerd in 'transpilers' zoals de Traceur Compiler, Babel of Rollup.

+
+ +

Syntax

+ +
export { name1, name2, …, nameN };
+export { variable1 as name1, variable2 as name2, …, nameN };
+export let name1, name2, …, nameN; // also var, function
+export let name1 = …, name2 = …, …, nameN; // also var, const
+export function FunctionName() {...}
+export class ClassName {...}
+
+export default expression;
+export default function (…) { … } // also class, function*
+export default function name1(…) { … } // also class, function*
+export { name1 as default, … };
+
+export * from …;
+export { name1, name2, …, nameN } from …;
+export { import1 as name1, import2 as name2, …, nameN } from …;
+export { default } from …;
+ +

 

+ +
+
nameN
+
Identificator die geëxporteerd moet worden (zodat het geïmporteerd kan worden via {{jsxref("Statements/import", "import")}} in een ander script).
+
+ +

Beschrijving

+ +

Er zijn 2 verschillende types van export: named en default. Er kunnen meerdere named exports per module bestaan, maar slechts een default export. Elk type komt overeen met een van de bovenstaande syntaxen.

+ + + +

Genoemde exports zijn handig om verschillende waardes te exporteren. Tijdens de import is het verplicht om dezelfde naam als het overeenkomende object te gebruiken.

+ +

Maar een standaard export kan geïmporteerd worden met enige andere naam, bijvoorbeeld:

+ +
let k; export default k = 12; // in bestand test.js
+
+import m from './test' // let op dat we de vrijheid hebben om import m te gebruiken in plaats van import k, omdat k een default export is.
+
+console.log(m);        // Zal '12' in de console laten zien
+
+ +

Er kan slechts 1 standaard export zijn.

+ +

De volgende syntax exporteert geen standaard export van de geïmporteerde module:

+ +
export * from …;
+ +

Gebruik de volgende syntax als de standaard export nodig is:

+ +
export {default} from 'mod';
+ +

Voorbeelden

+ +

Genoemde (named) exports gebruiken

+ +

In de module zouden we de volgende code kunnen gebruiken:

+ +
// module "my-module.js"
+function cube(x) {
+  return x * x * x;
+}
+const foo = Math.PI + Math.SQRT2;
+export { cube, foo };
+
+ +

Op deze manier zouden we in een ander script deze code kunnen hebben:

+ +
import { cube, foo } from 'my-module';
+console.log(cube(3)); // 27
+console.log(foo);    // 4.555806215962888
+ +

De standaard (default) export gebruiken

+ +

Als we een enkele waarde willen exporteren of willen terugvallen op een waarde voor onze module zouden we een standaard (default) export kunnen gebruiken:

+ +
// module "my-module.js"
+export default function cube(x) {
+  return x * x * x;
+}
+
+ +

Op die manier zal het vanzelfsprekend zijn om in een ander script de standaard (default) export te importeren:

+ +
import cube from 'my-module';
+console.log(cube(3)); // 27
+
+ +

Merk op dat het niet mogelijk is om var, let of const te gebruiken met export default.

+ +

Specificaties

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-exports', 'Exports')}}{{Spec2('ES2015')}}Initiële definitie.
{{SpecName('ESDraft', '#sec-exports', 'Exports')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibiliteit

+ + + +

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

+ +

Bekijk ook

+ + diff --git a/files/nl/web/javascript/reference/statements/index.html b/files/nl/web/javascript/reference/statements/index.html new file mode 100644 index 0000000000..af37d7c195 --- /dev/null +++ b/files/nl/web/javascript/reference/statements/index.html @@ -0,0 +1,149 @@ +--- +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.
+
{{jsxref("Statements/let", "let")}}
+
Declares a block scope local variable, optionally initializing it to a value.
+
{{jsxref("Statements/const", "const")}}
+
Declares a read-only named constant.
+
+ +

Functions and classes

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

Iterations

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

Others

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

Specifications

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

Browser compatibility

+ + + +

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

+ +

See also

+ + diff --git a/files/nl/web/javascript/reference/template_literals/index.html b/files/nl/web/javascript/reference/template_literals/index.html new file mode 100644 index 0000000000..ed698025ba --- /dev/null +++ b/files/nl/web/javascript/reference/template_literals/index.html @@ -0,0 +1,254 @@ +--- +title: Template literals +slug: Web/JavaScript/Reference/Template_literals +translation_of: Web/JavaScript/Reference/Template_literals +--- +
{{JsSidebar("More")}}
+ +

Template literals zijn strings met daar binnengesloten een expressie. Ze zijn te gebruiken met meerdere regels, en ook met string interpolation, ook een kenmerk van Javascript. Ze werden in eerdere versies dan ES2015 ook wel "template strings" genoemd.

+ +

Syntax

+ +
`string text`
+
+`string text line 1
+ string text line 2`
+
+`string text ${expression} string text`
+
+tag `string text ${expression} string text`
+
+ +

Beschrijving

+ +

Template literals beginnen en eindigen met een back tick, het accent grave symbool (` `)  (grave accent) in plaats van de gewone aanhalingstekens ("  ") of apostrof ('  ').  Template literals kunnen bestaan uit placeholders. Deze worden aangegeven met een dollar-teken en vervolgens accolades (${expression}). De expressie en tekst tussen de accolades worden doorgegeven aan een functie. The default functie plaatst alle delen achter elkaar. Als er een expressie voor de template literal staat, wordt de template string een tagged template literal genoemd. In dat geval wordt de expressie binnen de template literal doorgegeven aan de expressie (meestal een functie) zodat de template literal nog verder aangepast kan worden voordat de literal wordt weergegeven of doorgegeven.

+ +
let value = dummy`Ik ben ${name} en ik ben ${age} jaar`;
+
+function dummy() {
+   let str = "";
+   strings.forEach((string, i) => {
+       str += string + values[i];
+   });
+   return str;
+}
+
+ +

Om een back-tick in een template literal te gebruiken, moet er een backslash (\) voor de back-tick gebruikt worden (escaping).

+ +
`\`` === '`' // --> true
+ +

Meerdere regels

+ +

Any new line characters inserted in the source are part of the template literal. Using normal strings, you would have to use the following syntax in order to get multi-line strings:

+ +

Wordt binnen de template literal een nieuwe regel begonnen, dan maakt die regelopvoer deel uit van de template literal. Dit is anders dan met een gewone string; daar moet '\n' gebruikt worden om een string over meerdere regels toe te passen:

+ +
console.log('string text line 1\n' +
+'string text line 2');
+// "string text line 1
+// string text line 2"
+ +

Bij een template literal kan '\n' weggelaten worden:

+ +
console.log(`string text line 1
+string text line 2`);
+// "string text line 1
+// string text line 2"
+ +

Expression interpolation

+ +

Als er gerekend moet worden binnen een normale string, moet dat op de volgende manier gecodeerd worden:

+ +
var a = 5;
+var b = 10;
+console.log('Fifteen is ' + (a + b) + ' and\nnot ' + (2 * a + b) + '.');
+// "Fifteen is 15 and
+// not 20."
+ +

Met een template literal hoeft dat niet; de expressie kan tussen de accolades gezet worden. Dat verbetert de leesbaarheid:

+ +
var a = 5;
+var b = 10;
+console.log(`Fifteen is ${a + b} and
+not ${2 * a + b}.`);
+// "Fifteen is 15 and
+// not 20."
+ +

Nesting templates

+ +

Soms kan de leebaarheid vergroot worden door template literals binnen een andere template literal te gebruiken (nesting). Met andere woorden, binnen de  ${ } mag ook weer een template literal, voorzien van back-ticks gebruikt worden. Bijvoorbeeld:

+ +

In ES5:

+ +
var classes = 'header'
+classes += (isLargeScreen() ?
+   '' : item.isCollapsed ?
+     ' icon-expander' : ' icon-collapser');
+
+ +

In ES2015 met template literals, zonder nesting:

+ +
const classes = `header ${ isLargeScreen() ? '' :
+    (item.isCollapsed ? 'icon-expander' : 'icon-collapser') }`;
+ +

In ES2015 nu met nested template literals:

+ +
const classes = `header ${ isLargeScreen() ? '' :
+ `icon-${item.isCollapsed ? 'expander' : 'collapser'}` }`;
+ +

Tagged template literals

+ +

Een geavanceerde vorm van template literals zijn de tagged template literals. Hiermee kan de template literal verder gemanipuleerd worden in een functie. De eerste parameter van de tag functie is een array met strings. De volgende parameters zijn gerelateerd aan de expressie. Uiteindelijk kan de de geretourneerde string compleet aangepast worden. De naam van de tag functie kan net zoals bij gewone functies, vrij gekozen worden:

+ +
var person = 'Mike';
+var age = 28;
+
+function myTag(strings, personExp, ageExp) {
+
+  var str0 = strings[0]; // "that "
+  var str1 = strings[1]; // " is a "
+
+  // There is technically a string after
+  // the final expression (in our example),
+  // but it is empty (""), so disregard.
+  // var str2 = strings[2];
+
+  var ageStr;
+  if (ageExp > 99){
+    ageStr = 'centenarian';
+  } else {
+    ageStr = 'youngster';
+  }
+
+  return str0 + personExp + str1 + ageStr;
+
+}
+
+var output = myTag`that ${ person } is a ${ age }`;
+
+console.log(output);
+// that Mike is a youngster
+ +

Het is overigens niet noodzakelijk dat een tag functie weer een string retourneert:

+ +
function template(strings, ...keys) {
+  return (function(...values) {
+    var dict = values[values.length - 1] || {};
+    var result = [strings[0]];
+    keys.forEach(function(key, i) {
+      var value = Number.isInteger(key) ? values[key] : dict[key];
+      result.push(value, strings[i + 1]);
+    });
+    return result.join('');
+  });
+}
+
+var t1Closure = template`${0}${1}${0}!`;
+t1Closure('Y', 'A');  // "YAY!"
+var t2Closure = template`${0} ${'foo'}!`;
+t2Closure('Hello', {foo: 'World'});  // "Hello World!"
+
+ +

Raw strings

+ +

De speciale raw property, een property van het eerste functie argument, maakt het mogelijk de oorspronkelijke strings te benaderen, zonder de escape sequences.

+ +
function tag(strings) {
+  console.log(strings.raw[0]);
+}
+
+tag`string text line 1 \n string text line 2`;
+// logs "string text line 1 \n string text line 2" ,
+// including the two characters '\' and 'n'
+
+ +

De "String.raw()" method kan gebruikt worden om strings te maken op dezelfde manier als de standaard template function:

+ +
var str = String.raw`Hi\n${2+3}!`;
+// "Hi\n5!"
+
+str.length;
+// 6
+
+str.split('').join(',');
+// "H,i,\,n,5,!"
+
+ +

Tagged template literals and escape sequences

+ +

Volgens de ES2016 spec, tagged template literals conformeren zich tot de volgende escape reeksen:

+ + + +

Dit kan soms problemen geven:

+ +
latex`\unicode`
+// Throws in older ECMAScript versions (ES2016 and earlier)
+// SyntaxError: malformed Unicode character escape sequence
+ +

Tagged template literals zou andere taal elementen moeten toestaan, bijvoorbeeld DSLs of LaTeX waar andere escape reeksten normaal zijn. Het ECMAScript voorstel Template Literal Revision (stage 4, voor de ECMAScript 2018 standaard) zal hiermee rekening houden.

+ +

Escape reeksen zullen echter nu nog een undefined opleveren:

+ +
function latex(str) {
+ return { "cooked": str[0], "raw": str.raw[0] }
+}
+
+latex`\unicode`
+
+// { cooked: undefined, raw: "\\unicode" }
+ +

Let op dat alleen de restrictie bij tagged template literals wordt opgeheven, en niet bij untagged template literals:

+ +
let bad = `bad escape sequence: \unicode`;
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-template-literals', 'Template Literals')}}{{Spec2('ES2015')}}Initial definition. Defined in several section of the specification: Template Literals, Tagged Templates
{{SpecName('ESDraft', '#sec-template-literals', 'Template Literals')}}{{Spec2('ESDraft')}}Defined in several section of the specification: Template Literals, Tagged Templates
Template Literal RevisionStage 4 draftDrops escape sequence restriction from tagged template literals
+ +

Browser compatibility

+ +
+ + +

{{Compat("javascript.grammar.template_literals")}}

+
+ +

See also

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