From 1109132f09d75da9a28b649c7677bb6ce07c40c0 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:41:45 -0500 Subject: initial commit --- .../fa/web/javascript/reference/classes/index.html | 418 +++++++++++++++ .../fa/web/javascript/reference/errors/index.html | 31 ++ .../reference/errors/too_much_recursion/index.html | 114 ++++ .../reference/errors/unexpected_token/index.html | 84 +++ .../web/javascript/reference/functions/index.html | 596 ++++++++++++++++++++ .../reference/global_objects/array/index.html | 464 ++++++++++++++++ .../reference/global_objects/array/of/index.html | 102 ++++ .../global_objects/array/reduce/index.html | 579 ++++++++++++++++++++ .../reference/global_objects/function/index.html | 156 ++++++ .../javascript/reference/global_objects/index.html | 128 +++++ .../reference/global_objects/null/index.html | 126 +++++ .../reference/global_objects/regexp/index.html | 597 +++++++++++++++++++++ .../global_objects/regexp/test/index.html | 123 +++++ .../reference/global_objects/set/index.html | 459 ++++++++++++++++ files/fa/web/javascript/reference/index.html | 50 ++ .../web/javascript/reference/operators/index.html | 302 +++++++++++ .../web/javascript/reference/statements/index.html | 131 +++++ 17 files changed, 4460 insertions(+) create mode 100644 files/fa/web/javascript/reference/classes/index.html create mode 100644 files/fa/web/javascript/reference/errors/index.html create mode 100644 files/fa/web/javascript/reference/errors/too_much_recursion/index.html create mode 100644 files/fa/web/javascript/reference/errors/unexpected_token/index.html create mode 100644 files/fa/web/javascript/reference/functions/index.html create mode 100644 files/fa/web/javascript/reference/global_objects/array/index.html create mode 100644 files/fa/web/javascript/reference/global_objects/array/of/index.html create mode 100644 files/fa/web/javascript/reference/global_objects/array/reduce/index.html create mode 100644 files/fa/web/javascript/reference/global_objects/function/index.html create mode 100644 files/fa/web/javascript/reference/global_objects/index.html create mode 100644 files/fa/web/javascript/reference/global_objects/null/index.html create mode 100644 files/fa/web/javascript/reference/global_objects/regexp/index.html create mode 100644 files/fa/web/javascript/reference/global_objects/regexp/test/index.html create mode 100644 files/fa/web/javascript/reference/global_objects/set/index.html create mode 100644 files/fa/web/javascript/reference/index.html create mode 100644 files/fa/web/javascript/reference/operators/index.html create mode 100644 files/fa/web/javascript/reference/statements/index.html (limited to 'files/fa/web/javascript/reference') diff --git a/files/fa/web/javascript/reference/classes/index.html b/files/fa/web/javascript/reference/classes/index.html new file mode 100644 index 0000000000..e031309f9f --- /dev/null +++ b/files/fa/web/javascript/reference/classes/index.html @@ -0,0 +1,418 @@ +--- +title: Classes +slug: Web/JavaScript/Reference/Classes +tags: + - Classes + - Constructors + - ECMAScript 2015 + - Guide + - Inheritance + - Intermediate + - JavaScript + - NeedsTranslation + - TopicStub +translation_of: Web/JavaScript/Reference/Classes +--- +
{{JsSidebar("Classes")}}
+ +

Classes are a template for creating objects. They encapsulate data with code to work on that data. Classes in JS are built on prototypes but also have some syntax and semantics that are not shared with ES5 classalike semantics.

+ +

Defining classes

+ +

Classes are in fact "special functions", and just as you can define function expressions and function declarations, the class syntax has two components: class expressions and class declarations.

+ +

Class declarations

+ +

One way to define a class is using a class declaration. To declare a class, you use the class keyword with the name of the class ("Rectangle" here).

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

Hoisting

+ +

An important difference between function declarations and class declarations is that function declarations are hoisted and class declarations are not. You first need to declare your class and then access it, otherwise code like the following will throw a {{jsxref("ReferenceError")}}:

+ +
const p = new Rectangle(); // ReferenceError
+
+class Rectangle {}
+
+ +

Class expressions

+ +

A class expression is another way to define a class. Class expressions can be named or unnamed. The name given to a named class expression is local to the class's body. (it can be retrieved through the class's (not an instance's) {{jsxref("Function.name", "name")}} property, though).

+ +
// unnamed
+let Rectangle = class {
+  constructor(height, width) {
+    this.height = height;
+    this.width = width;
+  }
+};
+console.log(Rectangle.name);
+// output: "Rectangle"
+
+// named
+let Rectangle = class Rectangle2 {
+  constructor(height, width) {
+    this.height = height;
+    this.width = width;
+  }
+};
+console.log(Rectangle.name);
+// output: "Rectangle2"
+
+ +
+

Note: Class expressions are subject to the same hoisting restrictions as described in the Class declarations section.

+
+ +

Class body and method definitions

+ +

The body of a class is the part that is in curly brackets {}. This is where you define class members, such as methods or constructor.

+ +

Strict mode

+ +

The body of a class is executed in strict mode, i.e., code written here is subject to stricter syntax for increased performance, some otherwise silent errors will be thrown, and certain keywords are reserved for future versions of ECMAScript.

+ +

Constructor

+ +

The constructor method is a special method for creating and initializing an object created with a class. There can only be one special method with the name "constructor" in a class. A {{jsxref("SyntaxError")}} will be thrown if the class contains more than one occurrence of a constructor method.

+ +

A constructor can use the super keyword to call the constructor of the super class.

+ +

Prototype methods

+ +

See also method definitions.

+ +
class Rectangle {
+  constructor(height, width) {
+    this.height = height;
+    this.width = width;
+  }
+  // Getter
+  get area() {
+    return this.calcArea();
+  }
+  // Method
+  calcArea() {
+    return this.height * this.width;
+  }
+}
+
+const square = new Rectangle(10, 10);
+
+console.log(square.area); // 100
+ +

Static methods

+ +

The static keyword defines a static method for a class. Static methods are called without instantiating their class and cannot be called through a class instance. Static methods are often used to create utility functions for an application.

+ +
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.hypot(dx, dy);
+  }
+}
+
+const p1 = new Point(5, 5);
+const p2 = new Point(10, 10);
+p1.distance; //undefined
+p2.distance; //undefined
+
+console.log(Point.distance(p1, p2)); // 7.0710678118654755
+
+ +

Binding this with prototype and static methods

+ +

When a static or prototype method is called without a value for this, such as by assigning a variable to the method and then calling it, the this value will be undefined inside the method. This behavior will be the same even if the "use strict" directive isn't present, because code within the class body's syntactic boundary is always executed in strict mode.

+ +
class Animal {
+  speak() {
+    return this;
+  }
+  static eat() {
+    return this;
+  }
+}
+
+let obj = new Animal();
+obj.speak(); // the Animal object
+let speak = obj.speak;
+speak(); // undefined
+
+Animal.eat() // class Animal
+let eat = Animal.eat;
+eat(); // undefined
+ +

If we rewrite the above using traditional function-based syntax in non–strict mode, then this method calls is automatically bound to the initial this value, which by default is the global object. In strict mode, autobinding will not happen; the value of this remains as passed.

+ +
function Animal() { }
+
+Animal.prototype.speak = function() {
+  return this;
+}
+
+Animal.eat = function() {
+  return this;
+}
+
+let obj = new Animal();
+let speak = obj.speak;
+speak(); // global object (in non–strict mode)
+
+let eat = Animal.eat;
+eat(); // global object (in non-strict mode)
+
+ +

Instance properties

+ +

Instance properties must be defined inside of class methods:

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

Static (class-side) data properties and prototype data properties must be defined outside of the ClassBody declaration:

+ +
Rectangle.staticWidth = 20;
+Rectangle.prototype.prototypeWidth = 25;
+
+ +

Field declarations

+ +
+

Public and private field declarations are an experimental feature (stage 3) proposed at TC39, the JavaScript standards committee. Support in browsers is limited, but the feature can be used through a build step with systems like Babel.

+
+ +

Public field declarations

+ +

With the JavaScript field declaration syntax, the above example can be written as:

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

By declaring fields up-front, class definitions become more self-documenting, and the fields are always present.

+ +

As seen above, the fields can be declared with or without a default value.

+ +

See public class fields for more information.

+ +

Private field declarations

+ +

Using private fields, the definition can be refined as below.

+ +
class Rectangle {
+  #height = 0;
+  #width;
+  constructor(height, width) {
+    this.#height = height;
+    this.#width = width;
+  }
+}
+
+ +

It's an error to reference private fields from outside of the class; they can only be read or written within the class body. By defining things which are not visible outside of the class, you ensure that your classes' users can't depend on internals, which may change version to version.

+ +
+

Private fields can only be declared up-front in a field declaration.

+
+ +

Private fields cannot be created later through assigning to them, the way that normal properties can.

+ +

For more information, see private class fields.

+ +

Sub classing with extends

+ +

The extends keyword is used in class declarations or class expressions to create a class as a child of another class.

+ +
class Animal {
+  constructor(name) {
+    this.name = name;
+  }
+
+  speak() {
+    console.log(`${this.name} makes a noise.`);
+  }
+}
+
+class Dog extends Animal {
+  constructor(name) {
+    super(name); // call the super class constructor and pass in the name parameter
+  }
+
+  speak() {
+    console.log(`${this.name} barks.`);
+  }
+}
+
+let d = new Dog('Mitzie');
+d.speak(); // Mitzie barks.
+
+ +

If there is a constructor present in the subclass, it needs to first call super() before using "this".

+ +

One may also extend traditional function-based "classes":

+ +
function Animal (name) {
+  this.name = name;
+}
+
+Animal.prototype.speak = function () {
+  console.log(`${this.name} makes a noise.`);
+}
+
+class Dog extends Animal {
+  speak() {
+    console.log(`${this.name} barks.`);
+  }
+}
+
+let d = new Dog('Mitzie');
+d.speak(); // Mitzie barks.
+
+// For similar methods, the child's method takes precedence over parent's method
+ +

Note that classes cannot extend regular (non-constructible) objects. If you want to inherit from a regular object, you can instead use {{jsxref("Object.setPrototypeOf()")}}:

+ +
const Animal = {
+  speak() {
+    console.log(`${this.name} makes a noise.`);
+  }
+};
+
+class Dog {
+  constructor(name) {
+    this.name = name;
+  }
+}
+
+// If you do not do this you will get a TypeError when you invoke speak
+Object.setPrototypeOf(Dog.prototype, Animal);
+
+let d = new Dog('Mitzie');
+d.speak(); // Mitzie makes a noise.
+
+ +

Species

+ +

You might want to return {{jsxref("Array")}} objects in your derived array class MyArray. The species pattern lets you override default constructors.

+ +

For example, when using methods such as {{jsxref("Array.map", "map()")}} that returns the default constructor, you want these methods to return a parent Array object, instead of the MyArray object. The {{jsxref("Symbol.species")}} symbol lets you do this:

+ +
class MyArray extends Array {
+  // Overwrite species to the parent Array constructor
+  static get [Symbol.species]() { return Array; }
+}
+
+let a = new MyArray(1,2,3);
+let mapped = a.map(x => x * x);
+
+console.log(mapped instanceof MyArray); // false
+console.log(mapped instanceof Array);   // true
+
+ +

Super class calls with super

+ +

The super keyword is used to call corresponding methods of super class. This is one advantage over prototype-based inheritance.

+ +
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.`);
+  }
+}
+
+let l = new Lion('Fuzzy');
+l.speak();
+// Fuzzy makes a noise.
+// Fuzzy roars.
+
+ +

Mix-ins

+ +

Abstract subclasses or mix-ins are templates for classes. An ECMAScript class can only have a single superclass, so multiple inheritance from tooling classes, for example, is not possible. The functionality must be provided by the superclass.

+ +

A function with a superclass as input and a subclass extending that superclass as output can be used to implement mix-ins in ECMAScript:

+ +
let calculatorMixin = Base => class extends Base {
+  calc() { }
+};
+
+let randomizerMixin = Base => class extends Base {
+  randomize() { }
+};
+
+ +

A class that uses these mix-ins can then be written like this:

+ +
class Foo { }
+class Bar extends calculatorMixin(randomizerMixin(Foo)) { }
+ +

Specifications

+ + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-class-definitions', 'Class definitions')}}
+ +

Browser compatibility

+ + + +

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

+ +

Re-running a class definition

+ +

A class can't be redefined. Attempting to do so produces a SyntaxError.

+ +

If you're experimenting with code in a web browser, such as the Firefox Web Console (Tools > Web Developer > Web Console) and you 'Run' a definition of a class with the same name twice, you'll get a SyntaxError: redeclaration of let ClassName;. (See further discussion of this issue in bug 1428672.) Doing something similar in Chrome Developer Tools gives you a message like Uncaught SyntaxError: Identifier 'ClassName' has already been declared at <anonymous>:1:1.

+ +

See also

+ + diff --git a/files/fa/web/javascript/reference/errors/index.html b/files/fa/web/javascript/reference/errors/index.html new file mode 100644 index 0000000000..c295fccea6 --- /dev/null +++ b/files/fa/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/fa/web/javascript/reference/errors/too_much_recursion/index.html b/files/fa/web/javascript/reference/errors/too_much_recursion/index.html new file mode 100644 index 0000000000..02a8d54c45 --- /dev/null +++ b/files/fa/web/javascript/reference/errors/too_much_recursion/index.html @@ -0,0 +1,114 @@ +--- +title: 'InternalError: too much recursion' +slug: Web/JavaScript/Reference/Errors/Too_much_recursion +translation_of: Web/JavaScript/Reference/Errors/Too_much_recursion +--- +
{{jsSidebar("Errors")}}
+ +

Message

+ +
Error: Out of stack space (Edge)
+InternalError: too much recursion (Firefox)
+RangeError: Maximum call stack size exceeded (Chrome)
+
+ +

Error type

+ +

{{jsxref("InternalError")}}.

+ +

What went wrong?

+ +

A function that calls itself is called a recursive function. Once a condition is met, the function stops calling itself. This is called a base case.

+ +

In some ways, recursion is analogous to a loop. Both execute the same code multiple times, and both require a condition (to avoid an infinite loop, or rather, infinite recursion in this case). When there are too many function calls, or a function is missing a base case, JavaScript will throw this error.

+ +

Examples

+ +

This recursive function runs 10 times, as per the exit condition.

+ +
function loop(x) {
+  if (x >= 10) // "x >= 10" is the exit condition
+    return;
+  // do stuff
+  loop(x + 1); // the recursive call
+}
+loop(0);
+ +

Setting this condition to an extremely high value, won't work:

+ +
function loop(x) {
+  if (x >= 1000000000000)
+    return;
+  // do stuff
+  loop(x + 1);
+}
+loop(0);
+
+// InternalError: too much recursion
+ +

This recursive function is missing a base case. As there is no exit condition, the function will call itself infinitely.

+ +
function loop(x) {
+ // The base case is missing
+
+loop(x + 1); // Recursive call
+}
+
+loop(0);
+
+// InternalError: too much recursion
+ +

Class error: too much recursion

+ +
class Person{
+	constructor(){}
+	set name(name){
+		this.name = name; // Recursive call
+	}
+}
+
+
+const tony = new Person();
+tony.name = "Tonisha"; // InternalError: too much recursion
+
+ +

When a value is assigned to the property name (this.name = name;) JavaScript needs to set that property. When this happens, the setter function is triggered.

+ +
set name(name){
+	this.name = name; // Recursive call
+}
+
+ +
+

In this example when the setter is triggered, it is told to do the same thing again: to set the same property that it is meant to handle. This causes the function to call itself, again and again, making it infinitely recursive.

+
+ +

This issue also appears if the same variable is used in the getter.

+ +
get name(){
+	return this.name; // Recursive call
+}
+
+ +

To avoid this problem, make sure that the property being assigned to inside the setter function is different from the one that initially triggered the setter.The same goes for the getter.

+ +
class Person{
+	constructor(){}
+	set name(name){
+		this._name = name;
+	}
+	get name(){
+		return this._name;
+	}
+}
+const tony = new Person();
+tony.name = "Tonisha";
+console.log(tony);
+
+ +

See also

+ + diff --git a/files/fa/web/javascript/reference/errors/unexpected_token/index.html b/files/fa/web/javascript/reference/errors/unexpected_token/index.html new file mode 100644 index 0000000000..77fa2e06c5 --- /dev/null +++ b/files/fa/web/javascript/reference/errors/unexpected_token/index.html @@ -0,0 +1,84 @@ +--- +title: 'SyntaxError: Unexpected token' +slug: Web/JavaScript/Reference/Errors/Unexpected_token +translation_of: Web/JavaScript/Reference/Errors/Unexpected_token +--- +
+ +
+ +
+

{{jsSidebar("Errors")}}

+
+ +

The JavaScript exceptions "unexpected token" occur when a specific language construct was expected, but something else was provided. This might be a simple typo.

+ +

Message

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

Error type

+ +

{{jsxref("SyntaxError")}}

+ +

What went wrong?

+ +

A specific language construct was expected, but something else was provided. This might be a simple typo.

+ +

Examples

+ +

Expression expected

+ +

For example, when chaining expressions, trailing commas are not allowed.

+ +
for (let i = 0; i < 5,; ++i) {
+  console.log(i);
+}
+// SyntaxError: expected expression, got ')'
+
+ +

Correct would be omitting the comma or adding another expression:

+ +
for (let i = 0; i < 5; ++i) {
+  console.log(i);
+}
+
+ +

Not enough brackets

+ +

Sometimes, you leave out brackets around if statements:

+ +
function round(n, upperBound, lowerBound){
+  if(n > upperBound) || (n < lowerBound){
+    throw 'Number ' + String(n) + ' is more than ' + String(upperBound) + ' or less than ' + String(lowerBound);
+  }else if(n < ((upperBound + lowerBound)/2)){
+    return lowerBound;
+  }else{
+    return upperBound;
+  }
+} // SyntaxError: expected expression, got '||'
+ +

The brackets may look correct at first, but note how the || is outside the brackets. Correct would be putting brackets around the ||:

+ +
function round(n, upperBound, lowerBound){
+  if((n > upperBound) || (n < lowerBound)){
+    throw 'Number ' + String(n) + ' is more than ' + String(upperBound) + ' or less than ' + String(lowerBound);
+  }else if(n < ((upperBound + lowerBound)/2)){
+    return lowerBound;
+  }else{
+    return upperBound;
+  }
+}
+
+ +

See also

+ + diff --git a/files/fa/web/javascript/reference/functions/index.html b/files/fa/web/javascript/reference/functions/index.html new file mode 100644 index 0000000000..4f1c4136cc --- /dev/null +++ b/files/fa/web/javascript/reference/functions/index.html @@ -0,0 +1,596 @@ +--- +title: Functions +slug: Web/JavaScript/Reference/Functions +tags: + - Constructor + - Function + - Functions + - JavaScript + - NeedsTranslation + - Parameter + - TopicStub + - parameters +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.

+ +

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 {{jsxref("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). A function expression may be a part of a larger expression. One can define "named" function expressions (where the name of the expression might be used in the call stack for example) or "anonymous" function expressions. Function expressions are not hoisted onto the beginning of the scope, therefore they cannot be used before they appear in the code.

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

Here is an example of an anonymous function expression (the name is not used):

+ +
var myFunction = function() {
+    statements
+}
+ +

It is also possible to provide a name inside the definition in order to create a named function expression:

+ +
var myFunction = function namedFunction(){
+    statements
+}
+
+ +

One of the benefit of creating a named function expression is that in case we encounted an error, the stack trace will contain the name of the function, making it easier to find the origin of the error.

+ +

As we can see, both examples do not start with the function keyword. Statements involving functions which do not start with function are function expressions.

+ +

When functions are used only once, a common pattern is an IIFE (Immediately Invokable Function Expression).

+ +
(function() {
+    statements
+})();
+ +

IIFE are function expressions that are invoked as soon as the function is declared.

+ +

The generator function declaration (function* statement)

+ +

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)

+ +

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 (=>)

+ +

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: 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

+ +

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

+ +

Starting with ECMAScript 2015, 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:

+ +
var multiply = new Function('x', 'y', 'return x * y');
+ +

A function declaration of a function named multiply:

+ +
function multiply(x, y) {
+   return x * y;
+} // there is no semicolon here
+
+ +

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 in which the function is declared.

+ +

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 or by a function declaration 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).

+ +
/*
+ * Declare and initialize a variable 'p' (global)
+ * and a function 'myFunc' (to change the scope) inside which
+ * declare a varible with same name 'p' (current) and
+ * define three functions using three different ways:-
+ *     1. function declaration
+ *     2. function expression
+ *     3. function constructor
+ * each of which will log 'p'
+ */
+var p = 5;
+function myFunc() {
+    var p = 9;
+
+    function decl() {
+        console.log(p);
+    }
+    var expr = function() {
+        console.log(p);
+    };
+    var cons = new Function('\tconsole.log(p);');
+
+    decl();
+    expr();
+    cons();
+}
+myFunc();
+
+/*
+ * Logs:-
+ * 9  - for 'decl' by function declaration (current scope)
+ * 9  - for 'expr' by function expression (current scope)
+ * 5  - for 'cons' by Function constructor (global scope)
+ */
+
+ +

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

Block-level functions

+ +

In strict mode, starting with ES2015, functions inside blocks are now scoped to that block. Prior to ES2015, block-level functions were forbidden in strict mode.

+ +
'use strict';
+
+function f() {
+  return 1;
+}
+
+{
+  function f() {
+    return 2;
+  }
+}
+
+f() === 1; // true
+
+// f() === 2 in non-strict mode
+
+ +

Block-level functions in non-strict code

+ +

In a word: Don't.

+ +

In non-strict code, function declarations inside blocks behave strangely. For example:

+ +
if (shouldDefineZero) {
+   function zero() {     // DANGER: compatibility risk
+      console.log("This is zero.");
+   }
+}
+
+ +

ES2015 says that if shouldDefineZero is false, then zero should never be defined, since the block never executes. However, it's a new part of the standard. Historically, this was left unspecified, and some browsers would define zero whether the block executed or not.

+ +

In strict mode, all browsers that support ES2015 handle this the same way: zero is defined only if shouldDefineZero is true, and only in the scope of the if-block.

+ +

A safer way to define functions conditionally is to assign a function expression to a variable:

+ +
var zero;
+if (shouldDefineZero) {
+   zero = function() {
+      console.log("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 performed 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

+ + + +

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

+ +

See also

+ + diff --git a/files/fa/web/javascript/reference/global_objects/array/index.html b/files/fa/web/javascript/reference/global_objects/array/index.html new file mode 100644 index 0000000000..8780c0cb7b --- /dev/null +++ b/files/fa/web/javascript/reference/global_objects/array/index.html @@ -0,0 +1,464 @@ +--- +title: Array +slug: Web/JavaScript/Reference/Global_Objects/Array +tags: + - Array + - Example + - Global Objects + - JavaScript + - NeedsTranslation + - Reference + - TopicStub +translation_of: Web/JavaScript/Reference/Global_Objects/Array +--- +
{{JSRef}}
+ +
شیء Array در جاوااسکریپت یک شیء عمومی است که در ساخت آرایه ها استفاده می شود که اشیائی سطح بالا شبیه فهرست هستند.
+ +
+ +

ساخت یک آرایه

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

دسترسی به یک آیتم در آرایه (بر اساس نمایه)

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

اجرای حلقه روی آرایه

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

اضافه کردن به انتهای آرایه

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

حذف کردن از انتهای آرایه

+ +
var last = fruits.pop(); // remove Orange (from the end)
+// ["Apple", "Banana"];
+
+ +

حذف کردن از ابتدای آرایه

+ +
var first = fruits.shift(); // remove Apple from the front
+// ["Banana"];
+
+ +

اضافه کردن به ابتدای آرایه

+ +
var newLength = fruits.unshift('Strawberry') // add to the front
+// ["Strawberry", "Banana"];
+
+ +

پیدا کردن نمایه یک آیتم در یک آرایه

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

پاک کردن یک آیتم بر اساس موقعیت نمایه

+ +
var removedItem = fruits.splice(pos, 1); // this is how to remove an item
+
+// ["Strawberry", "Mango"]
+ +

پاک کردن آیتم ها بر اساس موقعیت نمایه

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

کپی کردن یک آرایه

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

Syntax

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

Parameters

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

Description

+ +

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

+ +

Arrays cannot use strings as element indexes (as in an associative array) but must use integers. Setting or accessing via non-integers using bracket notation (or dot notation) will not set or retrieve an element from the array list itself, but will set or access a variable associated with that array's object property collection. The array's object properties and list of array elements are separate, and the array's traversal and mutation operations cannot be applied to these named properties.

+ +

Accessing array elements

+ +

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

+ +
var arr = ['this is the first element', 'this is the second element', 'this is the last 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 last 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['var']);
+
+ +

Relationship between length and numerical properties

+ +

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

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

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

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

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

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

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

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

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

+ +

Creating an array using the result of a match

+ +

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

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

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

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

Properties

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

Methods

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

Array instances

+ +

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

+ +

Properties

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

Methods

+ +

Mutator methods

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

Accessor methods

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

Iteration methods

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

Array generic methods

+ +
+

Array generics are non-standard, deprecated and will get removed in the near future.

+
+ +

{{Obsolete_Header("Gecko71")}}

+ +

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 and they are not supported by non-Gecko browsers. As a standard alternative, you can convert your object to a proper array using {{jsxref("Array.from()")}}; although that method may not be supported in old browsers:

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

Examples

+ +

Creating an array

+ +

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

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

Creating a two-dimensional array

+ +

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

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

Here is the output:

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

Using an array to tabulate a set of values

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

Results in

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

(First column is the (index))

+ +

Specifications

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

Browser compatibility

+ + + +

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

+ +

See also

+ + diff --git a/files/fa/web/javascript/reference/global_objects/array/of/index.html b/files/fa/web/javascript/reference/global_objects/array/of/index.html new file mode 100644 index 0000000000..0c5aa6d2fa --- /dev/null +++ b/files/fa/web/javascript/reference/global_objects/array/of/index.html @@ -0,0 +1,102 @@ +--- +title: Array.of() +slug: Web/JavaScript/Reference/Global_Objects/Array/of +translation_of: Web/JavaScript/Reference/Global_Objects/Array/of +--- +
{{JSRef}}
+ +
متد Array.of() یک آرایه ی جدید شامل آرگومان های ارسال شده به آن میباشد میسازد، صرفنظر از تعداد و نوع آرگومان ها. 
+ +

تفاوت متد  Array.of() و متد سازنده ی  Array() در این میباشد که  Array.of(7) یک آرایه با یک المنت که مقدارش 7 میباشد میسازد. در حالیکه Array(7) یک آرایه ی جدید با طول 7 که شامل 7 المنت یا slot با مقدار empty میسازد نه با مقدار  undefined.

+ +
Array.of(7);       // [7]
+Array.of(1, 2, 3); // [1, 2, 3]
+
+Array(7);          // array of 7 empty slots
+Array(1, 2, 3);    // [1, 2, 3]
+
+ +

نحوه استفاده

+ +
Array.of(element0[, element1[, ...[, elementN]]])
+ +

پارامترها

+ +
+
elementN
+
لیست المنت هایی که باید درون آرایه قرار بگیرند.
+
+ +

مقدار بازگشتی

+ +

یک نمونه جدید از {{jsxref("Array")}} .

+ +

توضیحات

+ +

این تابع بخشی از ECMAScript 2015 استاندارد است. برای اطلاعات بیشتر لینک های زیر مراجعه کنید:

+ +

Array.of و Array.from proposal و Array.of polyfill.

+ +

مثال

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

چند کاره سازی

+ +

در صورت عدم وجود Array.of() به صورت پیشفرض، با اجرای کد زیر قبل اجرای سایر کدها، تابع  Array.of() را برای شما در کلاس Array پیاده سازی و قابل استفاده می نماید. برید حالشو ببرید.

+ +
if (!Array.of) {
+  Array.of = function() {
+    return Array.prototype.slice.call(arguments);
+    // Or
+    let vals = [];
+    for(let prop in arguments){
+        vals.push(arguments[prop]);
+    }
+    return vals;
+  }
+}
+
+ +

مشخصه ها

+ + + + + + + + + + + + + + + + + + + + + +
مشخصهوضعیتتوضیح
{{SpecName('ESDraft', '#sec-array.of', 'Array.of')}}{{Spec2('ESDraft')}}
{{SpecName('ES2015', '#sec-array.of', 'Array.of')}}{{Spec2('ES2015')}}Initial definition.
+ +

سازگاری با سایر مرورگرها

+ +
+ + +

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

+
+ +

همچنین ببینید

+ + diff --git a/files/fa/web/javascript/reference/global_objects/array/reduce/index.html b/files/fa/web/javascript/reference/global_objects/array/reduce/index.html new file mode 100644 index 0000000000..6145fa772e --- /dev/null +++ b/files/fa/web/javascript/reference/global_objects/array/reduce/index.html @@ -0,0 +1,579 @@ +--- +title: Array.prototype.reduce() +slug: Web/JavaScript/Reference/Global_Objects/Array/Reduce +translation_of: Web/JavaScript/Reference/Global_Objects/Array/Reduce +--- +
{{JSRef}}
+ +

 The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in a single output value.

+ +

متد reduce یک تابع reducer (کاهش دهنده) را بر روی هر کدام از المان‌های آرایه اجرا می‌کند و در خروجی یک آرایه برمی‌گرداند. توجه داشته باشید که تابع reducer را شما باید بنویسید.

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

یک تابع کاهش دهنده 4 آرگومان دریافت می‌کند

+ +

The reducer function takes four arguments:

+ +
    +
  1. Accumulator (acc) (انباشت کننده)
  2. +
  3. Current Value (cur) (مقدار فعلی)
  4. +
  5. Current Index (idx) (اندیس فعلی)
  6. +
  7. Source Array (src) (آرایه‌ی مبدا)
  8. +
+ +

Your reducer function's returned value is assigned to the accumulator, whose value is remembered across each iteration throughout the array and ultimately becomes the final, single resulting value.

+ +

بنابراین آرگومان اول تابع reduce، کاهش دهنده، و آرگومان دوم، انباشتگر می‌باشد. به این ترتیب پس از اعمال کاهش دهنده بر روی هر کدام از المان‌های آرایه، انباشت کننده یا اکیومیولیتور نیز اعمال اثر می‌کند.

+ +

Syntax

+ +
arr.reduce(callback(accumulator, currentValue[, index[, array]])[, initialValue])
+ +

Parameters

+ +
+
callback
+
A function to execute on each element in the array (except for the first, if no initialValue is supplied), taking four arguments: +
+
accumulator
+
The accumulator accumulates the callback's return values. It is the accumulated value previously returned in the last invocation of the callback, or initialValue, if supplied (see below).
+
currentValue
+
The current element being processed in the array.
+
index {{optional_inline}}
+
The index of the current element being processed in the array. Starts from index 0 if an initialValue is provided. Otherwise, starts from index 1.
+
array {{optional_inline}}
+
The array reduce() was called upon.
+
+
+
initialValue {{optional_inline}}
+
A value to use as the first argument to the first call of the callback. If no initialValue is supplied, the first element in the array will be used and skipped. Calling reduce() on an empty array without an initialValue will throw a TypeError.
+
+ +

Return value

+ +

The single value that results from the reduction.

+ +

مقدار بازگشتی مقداری واحد است.

+ +

Description

+ +

The reduce() method executes the callback once for each assigned value present in the array, taking four arguments:

+ +

تابع reduce، کال بک را یک بار بر روی مقدارهای الصاق شده در ارایه اعمال می کند و چهار ارگومان (ورودی) زیر را می پذیرد.

+ + + +

The first time the callback is called, accumulator and currentValue can be one of two values. If initialValue is provided in the call to reduce(), then accumulator will be equal to initialValue, and currentValue will be equal to the first value in the array. If no initialValue is provided, then accumulator will be equal to the first value in the array, and currentValue will be equal to the second.

+ +
+

Note: If initialValue is not provided, reduce() will execute the callback function starting at index 1, skipping the first index. If initialValue is provided, it will start at index 0.

+
+ +

If the array is empty and no initialValue is provided, {{jsxref("TypeError")}} will be thrown. If the array only has one element (regardless of position) and no initialValue is provided, or if initialValue is provided but the array is empty, the solo value will be returned without calling callback.

+ +

It is usually safer to provide an initialValue because there are three possible outputs without initialValue, as shown in the following example.

+ +

برای احتیاط بهتر است که همیشه یک initialValue یا مقدار اولیه درنظر گرفت زیرا در صورت در نظر نگرفتن مقدار اولیه سه حالت ممکن است رخ دهد که در مثال زیر توضیح داده شده است.

+ +
var maxCallback = ( acc, cur ) => Math.max( acc.x, cur.x );
+var maxCallback2 = ( max, cur ) => Math.max( max, cur );
+
+// reduce() without initialValue
+[ { x: 22 }, { x: 42 } ].reduce( maxCallback ); // 42
+[ { x: 22 }            ].reduce( maxCallback ); // { x: 22 }
+[                      ].reduce( maxCallback ); // TypeError
+
+// map/reduce; better solution, also works for empty or larger arrays
+[ { x: 22 }, { x: 42 } ].map( el => el.x )
+                        .reduce( maxCallback2, -Infinity );
+
+ +

How reduce() works

+ +

Suppose the following use of reduce() occurred:

+ +
[0, 1, 2, 3, 4].reduce(function(accumulator, currentValue, currentIndex, array) {
+  return accumulator + currentValue;
+});
+
+ +

The callback would be invoked four times, with the arguments and return values in each call being as follows:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
callbackaccumulatorcurrentValuecurrentIndexarrayreturn value
first call011[0, 1, 2, 3, 4]1
second call122[0, 1, 2, 3, 4]3
third call333[0, 1, 2, 3, 4]6
fourth call644[0, 1, 2, 3, 4]10
+ +

The value returned by reduce() would be that of the last callback invocation (10).

+ +

You can also provide an {{jsxref("Functions/Arrow_functions", "Arrow Function","",1)}} instead of a full function. The code below will produce the same output as the code in the block above:

+ +
[0, 1, 2, 3, 4].reduce( (accumulator, currentValue, currentIndex, array) => accumulator + currentValue );
+
+ +

If you were to provide an initialValue as the second argument to reduce(), the result would look like this:

+ +
[0, 1, 2, 3, 4].reduce((accumulator, currentValue, currentIndex, array) => {
+    return accumulator + currentValue;
+}, 10);
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
callbackaccumulatorcurrentValuecurrentIndexarrayreturn value
first call1000[0, 1, 2, 3, 4]10
second call1011[0, 1, 2, 3, 4]11
third call1122[0, 1, 2, 3, 4]13
fourth call1333[0, 1, 2, 3, 4]16
fifth call1644[0, 1, 2, 3, 4]20
+ +

The value returned by reduce() in this case would be 20.

+ +

Examples

+ +

Sum all the values of an array

+ +
var sum = [0, 1, 2, 3].reduce(function (accumulator, currentValue) {
+  return accumulator + currentValue;
+}, 0);
+// sum is 6
+
+
+ +

Alternatively written with an arrow function:

+ +
var total = [ 0, 1, 2, 3 ].reduce(
+  ( accumulator, currentValue ) => accumulator + currentValue,
+  0
+);
+ +

Sum of values in an object array

+ +

To sum up the values contained in an array of objects, you must supply an initialValue, so that each item passes through your function.

+ +
var initialValue = 0;
+var sum = [{x: 1}, {x: 2}, {x: 3}].reduce(function (accumulator, currentValue) {
+    return accumulator + currentValue.x;
+},initialValue)
+
+console.log(sum) // logs 6
+
+ +

Alternatively written with an arrow function:

+ +
var initialValue = 0;
+var sum = [{x: 1}, {x: 2}, {x: 3}].reduce(
+    (accumulator, currentValue) => accumulator + currentValue.x
+    ,initialValue
+);
+
+console.log(sum) // logs 6
+ +

Flatten an array of arrays

+ +
var flattened = [[0, 1], [2, 3], [4, 5]].reduce(
+  function(accumulator, currentValue) {
+    return accumulator.concat(currentValue);
+  },
+  []
+);
+// flattened is [0, 1, 2, 3, 4, 5]
+
+ +

Alternatively written with an arrow function:

+ +
var flattened = [[0, 1], [2, 3], [4, 5]].reduce(
+  ( accumulator, currentValue ) => accumulator.concat(currentValue),
+  []
+);
+
+ +

Counting instances of values in an object

+ +
var names = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice'];
+
+var countedNames = names.reduce(function (allNames, name) {
+  if (name in allNames) {
+    allNames[name]++;
+  }
+  else {
+    allNames[name] = 1;
+  }
+  return allNames;
+}, {});
+// countedNames is:
+// { 'Alice': 2, 'Bob': 1, 'Tiff': 1, 'Bruce': 1 }
+
+ +

Grouping objects by a property

+ +
var people = [
+  { name: 'Alice', age: 21 },
+  { name: 'Max', age: 20 },
+  { name: 'Jane', age: 20 }
+];
+
+function groupBy(objectArray, property) {
+  return objectArray.reduce(function (acc, obj) {
+    var key = obj[property];
+    if (!acc[key]) {
+      acc[key] = [];
+    }
+    acc[key].push(obj);
+    return acc;
+  }, {});
+}
+
+var groupedPeople = groupBy(people, 'age');
+// groupedPeople is:
+// {
+//   20: [
+//     { name: 'Max', age: 20 },
+//     { name: 'Jane', age: 20 }
+//   ],
+//   21: [{ name: 'Alice', age: 21 }]
+// }
+
+ +

Bonding arrays contained in an array of objects using the spread operator and initialValue

+ +
// friends - an array of objects
+// where object field "books" - list of favorite books
+var friends = [{
+  name: 'Anna',
+  books: ['Bible', 'Harry Potter'],
+  age: 21
+}, {
+  name: 'Bob',
+  books: ['War and peace', 'Romeo and Juliet'],
+  age: 26
+}, {
+  name: 'Alice',
+  books: ['The Lord of the Rings', 'The Shining'],
+  age: 18
+}];
+
+// allbooks - list which will contain all friends' books +
+// additional list contained in initialValue
+var allbooks = friends.reduce(function(accumulator, currentValue) {
+  return [...accumulator, ...currentValue.books];
+}, ['Alphabet']);
+
+// allbooks = [
+//   'Alphabet', 'Bible', 'Harry Potter', 'War and peace',
+//   'Romeo and Juliet', 'The Lord of the Rings',
+//   'The Shining'
+// ]
+ +

Remove duplicate items in array

+ +
+

Note: If you are using an environment compatible with {{jsxref("Set")}} and {{jsxref("Array.from()")}}, you could use let orderedArray = Array.from(new Set(myArray)); to get an array where duplicate items have been removed.

+
+ +
var myArray = ['a', 'b', 'a', 'b', 'c', 'e', 'e', 'c', 'd', 'd', 'd', 'd'];
+var myOrderedArray = myArray.reduce(function (accumulator, currentValue) {
+  if (accumulator.indexOf(currentValue) === -1) {
+    accumulator.push(currentValue);
+  }
+  return accumulator
+}, [])
+
+console.log(myOrderedArray);
+ +

Running Promises in Sequence

+ +
/**
+ * Runs promises from array of functions that can return promises
+ * in chained manner
+ *
+ * @param {array} arr - promise arr
+ * @return {Object} promise object
+ */
+function runPromiseInSequence(arr, input) {
+  return arr.reduce(
+    (promiseChain, currentFunction) => promiseChain.then(currentFunction),
+    Promise.resolve(input)
+  );
+}
+
+// promise function 1
+function p1(a) {
+  return new Promise((resolve, reject) => {
+    resolve(a * 5);
+  });
+}
+
+// promise function 2
+function p2(a) {
+  return new Promise((resolve, reject) => {
+    resolve(a * 2);
+  });
+}
+
+// function 3  - will be wrapped in a resolved promise by .then()
+function f3(a) {
+ return a * 3;
+}
+
+// promise function 4
+function p4(a) {
+  return new Promise((resolve, reject) => {
+    resolve(a * 4);
+  });
+}
+
+const promiseArr = [p1, p2, f3, p4];
+runPromiseInSequence(promiseArr, 10)
+  .then(console.log);   // 1200
+
+ +

Function composition enabling piping

+ +
// Building-blocks to use for composition
+const double = x => x + x;
+const triple = x => 3 * x;
+const quadruple = x => 4 * x;
+
+// Function composition enabling pipe functionality
+const pipe = (...functions) => input => functions.reduce(
+    (acc, fn) => fn(acc),
+    input
+);
+
+// Composed functions for multiplication of specific values
+const multiply6 = pipe(double, triple);
+const multiply9 = pipe(triple, triple);
+const multiply16 = pipe(quadruple, quadruple);
+const multiply24 = pipe(double, triple, quadruple);
+
+// Usage
+multiply6(6); // 36
+multiply9(9); // 81
+multiply16(16); // 256
+multiply24(10); // 240
+
+
+ +

write map using reduce

+ +
if (!Array.prototype.mapUsingReduce) {
+  Array.prototype.mapUsingReduce = function(callback, thisArg) {
+    return this.reduce(function(mappedArray, currentValue, index, array) {
+      mappedArray[index] = callback.call(thisArg, currentValue, index, array);
+      return mappedArray;
+    }, []);
+  };
+}
+
+[1, 2, , 3].mapUsingReduce(
+  (currentValue, index, array) => currentValue + index + array.length
+); // [5, 7, , 10]
+
+
+ +

Polyfill

+ +
// Production steps of ECMA-262, Edition 5, 15.4.4.21
+// Reference: http://es5.github.io/#x15.4.4.21
+// https://tc39.github.io/ecma262/#sec-array.prototype.reduce
+if (!Array.prototype.reduce) {
+  Object.defineProperty(Array.prototype, 'reduce', {
+    value: function(callback /*, initialValue*/) {
+      if (this === null) {
+        throw new TypeError( 'Array.prototype.reduce ' +
+          'called on null or undefined' );
+      }
+      if (typeof callback !== 'function') {
+        throw new TypeError( callback +
+          ' is not a function');
+      }
+
+      // 1. Let O be ? ToObject(this value).
+      var o = Object(this);
+
+      // 2. Let len be ? ToLength(? Get(O, "length")).
+      var len = o.length >>> 0;
+
+      // Steps 3, 4, 5, 6, 7
+      var k = 0;
+      var value;
+
+      if (arguments.length >= 2) {
+        value = arguments[1];
+      } else {
+        while (k < len && !(k in o)) {
+          k++;
+        }
+
+        // 3. If len is 0 and initialValue is not present,
+        //    throw a TypeError exception.
+        if (k >= len) {
+          throw new TypeError( 'Reduce of empty array ' +
+            'with no initial value' );
+        }
+        value = o[k++];
+      }
+
+      // 8. Repeat, while k < len
+      while (k < len) {
+        // a. Let Pk be ! ToString(k).
+        // b. Let kPresent be ? HasProperty(O, Pk).
+        // c. If kPresent is true, then
+        //    i.  Let kValue be ? Get(O, Pk).
+        //    ii. Let accumulator be ? Call(
+        //          callbackfn, undefined,
+        //          « accumulator, kValue, k, O »).
+        if (k in o) {
+          value = callback(value, o[k], k, o);
+        }
+
+        // d. Increase k by 1.
+        k++;
+      }
+
+      // 9. Return accumulator.
+      return value;
+    }
+  });
+}
+
+ +

If you need to support truly obsolete JavaScript engines that do not support Object.defineProperty(), it is best not to polyfill Array.prototype methods at all, as you cannot make them non-enumerable.

+ +

Specifications

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

Browser compatibility

+ +
+ + +

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

+
+ +

See also

+ + diff --git a/files/fa/web/javascript/reference/global_objects/function/index.html b/files/fa/web/javascript/reference/global_objects/function/index.html new file mode 100644 index 0000000000..4c80478bda --- /dev/null +++ b/files/fa/web/javascript/reference/global_objects/function/index.html @@ -0,0 +1,156 @@ +--- +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. Calling the constructor directly can create functions dynamically, but suffers from security and similar (but far less significant) performance issues to {{jsxref("eval")}}. However, unlike eval, the Function constructor creates functions which execute in the global scope only.

+ +
{{EmbedInteractiveExample("pages/js/function-constructor.html")}}
+ + + +

Every JavaScript function is actually a Function object. This can be seen with the code (function(){}).constructor === Function which returns true.

+ +

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. Omitting an argument will result in the value of that parameter being undefined.

+ +

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/Web/JavaScript/Reference/Global_Objects/Function/prototype', 'Properties')}}
+ +

Methods

+ +
{{page('/en-US/docs/Web/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".

+ +

Difference between Function constructor and function declaration

+ +

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 created. This is different from using {{jsxref("eval")}} with code for a function expression.

+ +
var x = 10;
+
+function createFunction1() {
+    var x = 20;
+    return new Function('return x;'); // this |x| refers global |x|
+}
+
+function createFunction2() {
+    var x = 20;
+    function f() {
+        return x; // this |x| refers local |x| above
+    }
+    return f;
+}
+
+var f1 = createFunction1();
+console.log(f1());          // 10
+var f2 = createFunction2();
+console.log(f2());          // 20
+
+ +

While this code works in web browsers, f1() will produce a ReferenceError in Node.js, as x will not be found. This is because the top-level scope in Node is not the global scope, and x will be local to the module.

+ +

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')}} 
{{SpecName('ESDraft', '#sec-function-objects', 'Function')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ +
+ + +

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

+
+ +

See also

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

Summary

+

This chapter documents all the JavaScript standard built-in objects, along with 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! Otherwise it returns undefined). The global object itself can be accessed by 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

+

Global properties returning a simple value.

+ +

Function properties

+

Global functions returning the result of a specific routine.

+ +

Fundamental objects

+

General language objects, functions and errors.

+ +

Numbers and dates

+

Objects dealing with numbers, dates and mathematical calculations.

+ +

Text processing

+

Objects for manipulating texts.

+ +

Indexed collections

+

Collections ordered by an index. Array-type objects.

+ +

Keyed collections

+

Collections of objects as keys. Elements iterable in insertion order.

+ +

Structured data

+

Data buffers and JavaScript Object Notation.

+ +

Control abstraction objects

+ +

Reflection

+ +

Internationalization

+

Additions to the ECMAScript core for language-sensitive functionalities.

+ +

Other

+ +
+

 

diff --git a/files/fa/web/javascript/reference/global_objects/null/index.html b/files/fa/web/javascript/reference/global_objects/null/index.html new file mode 100644 index 0000000000..b90e55a245 --- /dev/null +++ b/files/fa/web/javascript/reference/global_objects/null/index.html @@ -0,0 +1,126 @@ +--- +title: 'null' +slug: Web/JavaScript/Reference/Global_Objects/null +translation_of: Web/JavaScript/Reference/Global_Objects/null +--- +
 
+ +

مقدار null نمایان گر مقداری هست که به صورت دستی (عمدی) می توانیم به یک متغییر نسبت دهیم،null یکی از  {{Glossary("Primitive", "نوع های اولیه")}}. جاوا اسکریپت می باشد.

+ +

شیوه ی نوشتن

+ +
null
+ +

توضیح

+ +

null باید به صورت حروف کوچک نوشته شود،null اقلب برای مشخص کردن مکان object به کار برده می شود و به هیچ object وابسته نمی باشد

+ +

زمانی که می خواهید مقدار null یا undefined  را بررسی کنید به تفاوت مابین عملگر های بررسی (==) و (===) اگاه باشید.

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

تفاوت بین null  و undefined

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

مشخصات

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
مشخصاتوضعیتتوضیحات
{{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')}} 
+ +

سازگاری مرورگرها

+ +

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

بیشتر بخوانید

+ + diff --git a/files/fa/web/javascript/reference/global_objects/regexp/index.html b/files/fa/web/javascript/reference/global_objects/regexp/index.html new file mode 100644 index 0000000000..3419d5977b --- /dev/null +++ b/files/fa/web/javascript/reference/global_objects/regexp/index.html @@ -0,0 +1,597 @@ +--- +title: RegExp +slug: Web/JavaScript/Reference/Global_Objects/RegExp +tags: + - Constructor + - JavaScript + - NeedsTranslation + - RegExp + - Regular Expressions + - TopicStub +translation_of: Web/JavaScript/Reference/Global_Objects/RegExp +--- +
{{JSRef("Global_Objects", "RegExp")}}
+ +

Summary

+ +

The RegExp constructor creates a regular expression object for matching text with a pattern.

+ +

For an introduction on what  regular expressions are, read the Regular Expressions chapter in the JavaScript Guide.

+ +

Constructor

+ +

Literal and constructor notations are possible:

+ +
/pattern/flags;
+
+new RegExp(pattern [, flags]);
+
+ +

Parameters

+ +
+
pattern
+
The text of the regular expression.
+
flags
+
+

If specified, flags can have any combination of the following values:

+ +
+
g
+
global match
+
i
+
ignore case
+
m
+
multiline; treat beginning and end characters (^ and $) as working over multiple lines (i.e., match the beginning or end of each line (delimited by \n or \r), not only the very beginning or end of the whole input string)
+
y
+
sticky; matches only from the index indicated by the lastIndex property of this regular expression in the target string (and does not attempt to match from any later indexes).
+
+
+
+ +

Description

+ +

There are 2 ways to create a RegExp object: a literal notation and a constructor. To indicate strings, the parameters to the literal notation do not use quotation marks while the parameters to the constructor function do use quotation marks. So the following expressions create the same regular expression:

+ +
/ab+c/i;
+new RegExp("ab+c", "i");
+
+ +

The literal notation provides compilation of the regular expression when the expression is evaluated. Use literal notation when the regular expression will remain constant. For example, if you use literal notation to construct a regular expression used in a loop, the regular expression won't be recompiled on each iteration.

+ +

The constructor of the regular expression object, for example, new RegExp("ab+c"), provides runtime compilation of the regular expression. Use the constructor function when you know the regular expression pattern will be changing, or you don't know the pattern and are getting it from another source, such as user input.

+ +

When using the constructor function, the normal string escape rules (preceding special characters with \ when included in a string) are necessary. For example, the following are equivalent:

+ +
var re = /\w+/;
+var re = new RegExp("\\w+");
+
+ +

Special characters meaning in regular expressions

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Character Classes
CharacterMeaning
. +

(The dot, the decimal point) matches any single character except the newline characters: \n \r \u2028 or \u2029.

+ +

Note that the m multiline flag doesn't change the dot behavior. So to match a pattern across multiple lines the character set [^] can be used (if you don't mean an old version of IE, of course), it will match any character including newlines.

+ +

For example, /.y/ matches "my" and "ay", but not "yes", in "yes make my day".

+
\d +

Matches a digit character in the basic Latin alphabet. Equivalent to [0-9].

+ +

For example, /\d/ or /[0-9]/ matches '2' in "B2 is the suite number."

+
\D +

Matches any character that is not a digit in the basic Latin alphabet. Equivalent to [^0-9].

+ +

For example, /\D/ or /[^0-9]/ matches 'B' in "B2 is the suite number."

+
\w +

Matches any alphanumeric character from the basic Latin alphabet, including the underscore. Equivalent to [A-Za-z0-9_].

+ +

For example, /\w/ matches 'a' in "apple," '5' in "$5.28," and '3' in "3D."

+
\W +

Matches any character that is not a word character from the basic Latin alphabet. Equivalent to [^A-Za-z0-9_].

+ +

For example, /\W/ or /[^A-Za-z0-9_]/ matches '%' in "50%."

+
\s +

Matches a single white space character, including space, tab, form feed, line feed and other Unicode spaces. Equivalent to [ \f\n\r\t\v​\u00a0\u1680​\u180e\u2000​\u2001\u2002​\u2003\u2004​ \u2005\u2006​\u2007\u2008​\u2009\u200a​\u2028\u2029​​\u202f\u205f​ \u3000].

+ +

For example, /\s\w*/ matches ' bar' in "foo bar."

+
\S +

Matches a single character other than white space. Equivalent to [^ \f\n\r\t\v​\u00a0\u1680​\u180e\u2000​\u2001\u2002​\u2003\u2004​ \u2005\u2006​\u2007\u2008​\u2009\u200a​\u2028\u2029​\u202f\u205f​\u3000].

+ +

For example, /\S\w*/ matches 'foo' in "foo bar."

+
\tMatches a tab.
\rMatches a carriage return.
\nMatches a linefeed.
\vMatches a vertical tab.
\fMatches a form-feed.
[\b]Matches a backspace. (Not to be confused with \b)
\0Matches a NUL character. Do not follow this with another digit.
\cX +

Where X is a letter from A - Z. Matches a control character in a string.

+ +

For example, /\cM/ matches control-M in a string.

+
\xhhMatches the character with the code hh (two hexadecimal digits)
\uhhhhMatches the character with the Unicode value hhhh (four hexadecimal digits).
\ +

For characters that are usually treated literally, indicates that the next character is special and not to be interpreted literally.

+ +

For example, /b/ matches the character 'b'. By placing a backslash in front of b, that is by using /\b/, the character becomes special to mean match a word boundary.

+ +

or

+ +

For characters that are usually treated specially, indicates that the next character is not special and should be interpreted literally.

+ +

For example, * is a special character that means 0 or more occurrences of the preceding character should be matched; for example, /a*/ means match 0 or more "a"s. To match * literally, precede it with a backslash; for example, /a\*/ matches 'a*'.

+
+

Character Sets

+
CharacterMeaning
[xyz] +

A character set. Matches any one of the enclosed characters. You can specify a range of characters by using a hyphen.

+ +

For example, [abcd] is the same as [a-d]. They match the 'b' in "brisket" and the 'c' in "chop".

+
[^xyz] +

A negated or complemented character set. That is, it matches anything that is not enclosed in the brackets. You can specify a range of characters by using a hyphen.

+ +

For example, [^abc] is the same as [^a-c]. They initially match 'o' in "bacon" and 'h' in "chop."

+
Boundaries
CharacterMeaning
^ +

Matches beginning of input. If the multiline flag is set to true, also matches immediately after a line break character.

+ +

For example, /^A/ does not match the 'A' in "an A", but does match the first 'A' in "An A."

+
$ +

Matches end of input. If the multiline flag is set to true, also matches immediately before a line break character.

+ +

For example, /t$/ does not match the 't' in "eater", but does match it in "eat".

+
\b +

Matches a zero-width word boundary, such as between a letter and a space. (Not to be confused with [\b])

+ +

For example, /\bno/ matches the 'no' in "at noon"; /ly\b/ matches the 'ly' in "possibly yesterday."

+
\B +

Matches a zero-width non-word boundary, such as between two letters or between two spaces.

+ +

For example, /\Bon/ matches 'on' in "at noon", and /ye\B/ matches 'ye' in "possibly yesterday."

+
Grouping and back references
CharacterMeaning
(x) +

Matches x and remembers the match. These are called capturing parentheses.

+ +

For example, /(foo)/ matches and remembers 'foo' in "foo bar." The matched substring can be recalled from the resulting array's elements [1], ..., [n] or from the predefined RegExp object's properties $1, ..., $9.

+ +

Capturing groups have a performance penalty. If you don't need the matched substring to be recalled, prefer non-capturing parentheses (see below).

+
\n +

Where n is a positive integer. A back reference to the last substring matching the n parenthetical in the regular expression (counting left parentheses).

+ +

For example, /apple(,)\sorange\1/ matches 'apple, orange,' in "apple, orange, cherry, peach." A more complete example follows this table.

+
(?:x)Matches x but does not remember the match. These are called non-capturing parentheses. The matched substring can not be recalled from the resulting array's elements [1], ..., [n] or from the predefined RegExp object's properties $1, ..., $9.
Quantifiers
CharacterMeaning
x* +

Matches the preceding item x 0 or more times.

+ +

For example, /bo*/ matches 'boooo' in "A ghost booooed" and 'b' in "A bird warbled", but nothing in "A goat grunted".

+
x+ +

Matches the preceding item x 1 or more times. Equivalent to {1,}.

+ +

For example, /a+/ matches the 'a' in "candy" and all the a's in "caaaaaaandy".

+
x*?
+ x+?
+

Matches the preceding item x like * and + from above, however the match is the smallest possible match.

+ +

For example, /".*?"/ matches '"foo"' in '"foo" "bar"' and does not match '"foo" "bar"' as without the ? behind the *.

+
x? +

Matches the preceding item x 0 or 1 time.

+ +

For example, /e?le?/ matches the 'el' in "angel" and the 'le' in "angle."

+ +

If used immediately after any of the quantifiers *, +, ?, or {}, makes the quantifier non-greedy (matching the minimum number of times), as opposed to the default, which is greedy (matching the maximum number of times).

+ +

Also used in lookahead assertions, described under (?=), (?!), and (?:) in this table.

+
x(?=y)Matches x only if x is followed by y. For example, /Jack(?=Sprat)/ matches 'Jack' only if it is followed by 'Sprat'. /Jack(?=Sprat|Frost)/ matches 'Jack' only if it is followed by 'Sprat' or 'Frost'. However, neither 'Sprat' nor 'Frost' is part of the match results.
x(?!y) +

Matches x only if x is not followed by y. For example, /\d+(?!\.)/ matches a number only if it is not followed by a decimal point.

+ +

/\d+(?!\.)/.exec("3.141") matches 141 but not 3.141.

+
x|y +

Matches either x or y.

+ +

For example, /green|red/ matches 'green' in "green apple" and 'red' in "red apple."

+
x{n} +

Where n is a positive integer. Matches exactly n occurrences of the preceding item x.

+ +

For example, /a{2}/ doesn't match the 'a' in "candy," but it matches all of the a's in "caandy," and the first two a's in "caaandy."

+
x{n,} +

Where n is a positive integer. Matches at least n occurrences of the preceding item x.

+ +

For example, /a{2,}/ doesn't match the 'a' in "candy", but matches all of the a's in "caandy" and in "caaaaaaandy."

+
x{n,m} +

Where n and m are positive integers. Matches at least n and at most m occurrences of the preceding item x.

+ +

For example, /a{1,3}/ matches nothing in "cndy", the 'a' in "candy," the two a's in "caandy," and the first three a's in "caaaaaaandy". Notice that when matching "caaaaaaandy", the match is "aaa", even though the original string had more a's in it.

+
+ +

Properties

+ +
+
{{jsxref("RegExp.prototype")}}
+
Allows the addition of properties to all objects.
+
RegExp.length
+
The value of RegExp.length is 2.
+
+ +
{{jsOverrides("Function", "Properties", "prototype")}}
+ +

Methods

+ +

The global RegExp object has no methods of its own, however, it does inherit some methods through the prototype chain.

+ +
{{jsOverrides("Function", "Methods", "prototype")}}
+ +

RegExp prototype objects and instances

+ +

Properties

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

Methods

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

Examples

+ +

Example: Using a regular expression to change data format

+ +

The following script uses the {{jsxref("String.replace", "replace")}} method of the {{jsxref("Global_Objects/String", "String")}} instance to match a name in the format first last and output it in the format last, first. In the replacement text, the script uses $1 and $2 to indicate the results of the corresponding matching parentheses in the regular expression pattern.

+ +
var re = /(\w+)\s(\w+)/;
+var str = "John Smith";
+var newstr = str.replace(re, "$2, $1");
+console.log(newstr);
+ +

This displays "Smith, John".

+ +

Example: Using regular expression on multiple lines

+ +
var s = "Please yes\nmake my day!";
+s.match(/yes.*day/);
+// Returns null
+s.match(/yes[^]*day/);
+// Returns 'yes\nmake my day'
+
+ +

Example: Using a regular expression with the "sticky" flag

+ +

This example demonstrates how one could use the sticky flag on regular expressions to match individual lines of multiline input.

+ +
var text = "First line\nSecond line";
+var regex = /(\S+) line\n?/y;
+
+var match = regex.exec(text);
+console.log(match[1]);  // prints "First"
+console.log(regex.lastIndex); // prints 11
+
+var match2 = regex.exec(text);
+console.log(match2[1]); // prints "Second"
+console.log(regex.lastIndex); // prints "22"
+
+var match3 = regex.exec(text);
+console.log(match3 === null); // prints "true"
+ +

One can test at run-time whether the sticky flag is supported, using try { … } catch { … }. For this, either an eval(…) expression or the RegExp(regex-string, flags-string) syntax must be used (since the /regex/flags notation is processed at compile-time, so throws an exception before the catch block is encountered). For example:

+ +
var supports_sticky;
+try { RegExp('','y'); supports_sticky = true; }
+catch(e) { supports_sticky = false; }
+alert(supports_sticky); // alerts "true"
+ +

Example: Regular expression and Unicode characters

+ +

As mentioned above, \w or \W only matches ASCII based characters; for example, 'a' to 'z', 'A' to 'Z', 0 to 9 and '_'. To match characters from other languages such as Cyrillic or Hebrew, use \uhhhh., where "hhhh" is the character's Unicode value in hexadecimal. This example demonstrates how one can separate out Unicode characters from a word.

+ +
var text = "Образец text на русском языке";
+var regex = /[\u0400-\u04FF]+/g;
+
+var match = regex.exec(text);
+console.log(match[0]);  // prints "Образец"
+console.log(regex.lastIndex);  // prints "7"
+
+var match2 = regex.exec(text);
+console.log(match2[0]);  // prints "на" [did not print "text"]
+console.log(regex.lastIndex);  // prints "15"
+
+// and so on
+ +

Here's an external resource for getting the complete Unicode block range for different scripts: Regexp-unicode-block

+ +

Example: Extracting subdomain name from URL

+ +
var url = "http://xxx.domain.com";
+console.log(/[^.]+/.exec(url)[0].substr(7)); // prints "xxx"
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
ECMAScript 1st Edition. Implemented in JavaScript 1.1StandardInitial definition.
{{SpecName('ES5.1', '#sec-15.10', 'RegExp')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-regexp-regular-expression-objects', 'RegExp')}}{{Spec2('ES6')}} 
+ +

Browser compatibility

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
Sticky flag ("y")39 (behind flag){{ CompatGeckoDesktop("1.9") }} ES4-Style {{bug(773687)}}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
Sticky flag ("y"){{ CompatNo() }}{{ CompatNo() }}{{ CompatGeckoDesktop("1.9") }} ES4-Style {{bug(773687)}}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
+
+ +

See also

+ + diff --git a/files/fa/web/javascript/reference/global_objects/regexp/test/index.html b/files/fa/web/javascript/reference/global_objects/regexp/test/index.html new file mode 100644 index 0000000000..1690ceb375 --- /dev/null +++ b/files/fa/web/javascript/reference/global_objects/regexp/test/index.html @@ -0,0 +1,123 @@ +--- +title: RegExp.prototype.test() +slug: Web/JavaScript/Reference/Global_Objects/RegExp/test +tags: + - جاوا اسکریپت + - جستجو + - متد +translation_of: Web/JavaScript/Reference/Global_Objects/RegExp/test +--- +
+ {{JSRef("Global_Objects", "RegExp")}}
+

خلاصه

+

متد test یک جستجو برای یافتن رشته خاص در متن یا رشته مورد نظر انجام میدهد و True یا False برمیگرداند.

+

ساختار

+
regexObj.test(str)
+

پارامتر ها

+
+
+ str
+
+ رشته ای که میخواهید با متن مورد نظر تطابق دهید.
+
+

مقدار بازگشتی

+

مقدار بازگشتی از نوع Boolean بوده و True یا False میباشد.

+

توضیحات

+

متد test() زمانی استفاده میشود که میخواهید الگو مورد نظر خود را در یک متن جستجو کنید و از وجود آن در متن مورد نظر با خبر شوید.

+

متدهای مرتبط : {jsxref("String.search") , {jsxref("RegExp.exec", "exec")

+

مثال

+

مثال: استفاده از test

+

مثال زیر یک خروجی را چاپ میکند که اشاره به موفقیت آمیز بودن جستجو دارد:

+
function testinput(re, str){
+    var midstring;
+    if (re.test(str)) {
+        midstring = " contains ";
+    } else {
+        midstring = " does not contain ";
+    }
+    console.log(str + midstring + re.source);
+}
+
+

خصوصیات

+ + + + + + + + + + + + + + + + + + + + + + + +
خصوصیتوضعیتیاداشت
ECMAScript 3rd Edition. Implemented in JavaScript 1.2StandardInitial definition.
{{SpecName('ES5.1', '#sec-15.10.6.3', 'RegExp.test')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-regexp.prototype.test', 'RegExp.test')}}{{Spec2('ES6')}} 
+

سازگاری با مرورگرها

+

{{ CompatibilityTable() }}

+
+ + + + + + + + + + + + + + + + + + + +
خصوصیاتگوگل کرومفایرفاکساینترنت اکسپلورراپراسافاری
پشتیبانی ابتدایی{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+
+ + + + + + + + + + + + + + + + + + + + + +
خصوصیاتاندرویدگوگل کروم برای اندرویدفایرفاکس موبایلاینترنت اکسپلورر موبایلاپرا موبایلسافاری موبایل
پشتیبانی ابتدایی{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+

 

+

یادداشتی برای Gecko-specific

+

قبل از نسخه Gecko 8.0 {{ geckoRelease("8.0") }} تابع test() مشکلاتی به همراه داشت ، زمانی که این تابع بدون پارامتر ورودی فراخوانی میشد الگو را با متن قبلی مطابقت میداد (RegExp.input property) در حالی که بایستی رشته "undefined" را قرار میداد. در حال حاضر این مشکل برطرف شده است و این تابع به درستی کار میکند.

+

 

+

 

+

همچنین سری بزنید به :

+ diff --git a/files/fa/web/javascript/reference/global_objects/set/index.html b/files/fa/web/javascript/reference/global_objects/set/index.html new file mode 100644 index 0000000000..c756b38195 --- /dev/null +++ b/files/fa/web/javascript/reference/global_objects/set/index.html @@ -0,0 +1,459 @@ +--- +title: مجموعه | Set +slug: Web/JavaScript/Reference/Global_Objects/Set +tags: + - جاوااسکریپت + - مجموعه +translation_of: Web/JavaScript/Reference/Global_Objects/Set +--- +
+
{{JSRef}}
+ +
شیء Set به شما اجازه می‌دهد مجموعه‌ای از مقادیر منحصر به فرد را از هر نوعی که باشند ذخیره کنید، چه {{Glossary("Primitive", "مقادیر اوّلیّه (Primitive)")}} باشند، چه ارجاع‌هایی به اشیاء.
+ +

Syntax

+ +
new Set([iterable]);
+ +

پارامترها

+ +
+
iterable
+
اگر یک شیء قابل شمارش (iterable) باشد، همه‌ی عناصر آن به مجموعه‌ی جدید ما اضافه می‌شوند. null نیز در این‌جا به منزله‌ی undefined است.
+
+ +

توضیح

+ +

هر شیء Set مجموعه‌ای از مقادیر است. این مقادیر به ترتیبی که به مجموعه اضافه شدند شمارش می‌شوند. یک مقدار در مجموعه فقط می‌تواند یک بار بیاید (مهم‌ترین تفاوت مجموعه و آرایه در همین است که در مجموعه مقدار تکراری نداریم ولی در آرایه می‌توانیم داشته باشیم).

+ +

برابر بودن مقدارها

+ +

از آن جایی که در هر مجموعه باید مقادیر منحصر به فرد داشته باشیم، به صورت خودکار هنگام اضافه شدن عضو جدید به مجموعه برابری مقدارها بررسی می‌شود. در نسخه‌های قبلی ECMAScript، الگوریتمی که این بررسی استفاده می‌کرد با الگوریتم عملگر === فرق داشت. مخصوصا برای مجموعه‌ها عدد صفر مثبت +0 با صفر منفی -0 متفاوت در نظر گرفته می‌شدند. با این حال در مشخّصاتی که برای ECMAScript 2015 در نظر گرفته شد این مورد تغییر کرد. برای اطّلاعات بیشتر جدول پشتیبانی مرورگرها از برابری صفر مثبت و منفی را ببینید.

+ +

ضمناً NaN و undefined نیز می‌توانند در یک مجموعه ذخیره شوند. در این مورد NaN با NaN برابر در نظر گرفته می‌شود (در حالی که به صورت عادی NaN !== NaN است).

+ +

خصیصه‌ها

+ +
+
Set.length
+
مقدار خصیصه‌ی length همیشه 0 است!
+
{{jsxref("Set.@@species", "get Set[@@species]")}}
+
تابع سازنده‌ای است که برای اشیاء مشتق شده به کار می‌رود.
+
{{jsxref("Set.prototype")}}
+
نشان‌دهنده‌ی prototype تابع سازنده‌ی Set است که اجازه می‌دهد خصیصه‌های جدیدی را به تمام اشیائی که از نوع مجموعه هستند اضافه کنید.
+
+ +

Set instances

+ +

تمام نمونه‌های کلاس Set از {{jsxref("Set.prototype")}} ارث‌بری می‌کنند.

+ +

خصیصه‌ها

+ +

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

+ +

متُدها

+ +

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

+ +

مثال‌ها

+ +

استفاده از شیء Set

+ +
var mySet = new Set();
+
+mySet.add(1);
+mySet.add(5);
+mySet.add("some text");
+var o = {a: 1, b: 2};
+mySet.add(o);
+
+mySet.add({a: 1, b: 2}); // o is referencing a different object so this is okay
+
+mySet.has(1); // true
+mySet.has(3); // false, 3 has not been added to the set
+mySet.has(5);              // true
+mySet.has(Math.sqrt(25));  // true
+mySet.has("Some Text".toLowerCase()); // true
+mySet.has(o); // true
+
+mySet.size; // 4
+
+mySet.delete(5); // removes 5 from the set
+mySet.has(5);    // false, 5 has been removed
+
+mySet.size; // 3, we just removed one value
+
+ +

شمارش عناصر مجموعه

+ +
// iterate over items in set
+// logs the items in the order: 1, "some text", {"a": 1, "b": 2}
+for (let item of mySet) console.log(item);
+
+// logs the items in the order: 1, "some text", {"a": 1, "b": 2}
+for (let item of mySet.keys()) console.log(item);
+
+// logs the items in the order: 1, "some text", {"a": 1, "b": 2}
+for (let item of mySet.values()) console.log(item);
+
+// logs the items in the order: 1, "some text", {"a": 1, "b": 2}
+//(key and value are the same here)
+for (let [key, value] of mySet.entries()) console.log(key);
+
+// convert Set object to an Array object, with Array.from
+var myArr = Array.from(mySet); // [1, "some text", {"a": 1, "b": 2}]
+
+// the following will also work if run in an HTML document
+mySet.add(document.body);
+mySet.has(document.querySelector("body")); // true
+
+// converting between Set and Array
+mySet2 = new Set([1,2,3,4]);
+mySet2.size; // 4
+[...mySet2]; // [1,2,3,4]
+
+// intersect can be simulated via
+var intersection = new Set([...set1].filter(x => set2.has(x)));
+
+// difference can be simulated via
+var difference = new Set([...set1].filter(x => !set2.has(x)));
+
+// Iterate set entries with forEach
+mySet.forEach(function(value) {
+  console.log(value);
+});
+
+// 1
+// 2
+// 3
+// 4
+ +

پیاده‌سازی عمل‌های اصلی در مجموعه‌ها

+ +
Set.prototype.isSuperset = function(subset) {
+    for (var elem of subset) {
+        if (!this.has(elem)) {
+            return false;
+        }
+    }
+    return true;
+}
+
+Set.prototype.union = function(setB) {
+    var union = new Set(this);
+    for (var elem of setB) {
+        union.add(elem);
+    }
+    return union;
+}
+
+Set.prototype.intersection = function(setB) {
+    var intersection = new Set();
+    for (var elem of setB) {
+        if (this.has(elem)) {
+            intersection.add(elem);
+        }
+    }
+    return intersection;
+}
+
+Set.prototype.difference = function(setB) {
+    var difference = new Set(this);
+    for (var elem of setB) {
+        difference.delete(elem);
+    }
+    return difference;
+}
+
+//Examples
+var setA = new Set([1,2,3,4]),
+    setB = new Set([2,3]),
+    setC = new Set([3,4,5,6]);
+
+setA.isSuperset(setB); // => true
+setA.union(setC); // => Set [1, 2, 3, 4, 5, 6]
+setA.intersection(setC); // => Set [3, 4]
+setA.difference(setC); // => Set [1, 2]
+
+
+ +

ارتباط مجموعه و آرایه

+ +
var myArray = ["value1", "value2", "value3"];
+
+// Use the regular Set constructor to transform an Array into a Set
+var mySet = new Set(myArray);
+
+mySet.has("value1"); // returns true
+
+// Use the spread operator to transform a set into an Array.
+console.log([...mySet]); // Will show you exactly the same Array as myArray
+ +

مشخّصات

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES6', '#sec-set-objects', 'Set')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-set-objects', 'Set')}}{{Spec2('ESDraft')}} 
+ +

سازگاری با مرورگرها

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ویژگیChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
پشتیبانی ساده +

{{ CompatChrome(38) }} [1]

+
12{{ CompatGeckoDesktop("13") }}{{ CompatIE("11") }}257.1
Constructor argument: new Set(iterable){{ CompatChrome(38) }}12{{ CompatGeckoDesktop("13") }}{{CompatNo}}259.0
iterable{{ CompatChrome(38) }}12{{ CompatGeckoDesktop("17") }}{{CompatNo}}257.1
Set.clear(){{ CompatChrome(38) }}12{{CompatGeckoDesktop("19")}}{{ CompatIE("11") }}257.1
Set.keys(), Set.values(), Set.entries(){{ CompatChrome(38) }}12{{CompatGeckoDesktop("24")}}{{CompatNo}}257.1
Set.forEach(){{ CompatChrome(38) }}12{{CompatGeckoDesktop("25")}}{{ CompatIE("11") }}257.1
Value equality for -0 and 0{{ CompatChrome(38) }}12{{CompatGeckoDesktop("29")}}{{CompatNo}}25{{CompatSafari(9)}}
Constructor argument: new Set(null){{CompatVersionUnknown}}12{{CompatGeckoDesktop("37")}}{{CompatIE(11)}}{{CompatVersionUnknown}}{{CompatSafari(7.1)}}
Monkey-patched add() in Constructor{{CompatVersionUnknown}}12{{CompatGeckoDesktop("37")}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatSafari(9)}}
Set[@@species]{{ CompatChrome(51) }}13{{CompatGeckoDesktop("41")}}{{CompatNo}}{{ CompatOpera(38) }}{{CompatSafari(10)}}
Set() without new throws{{CompatVersionUnknown}}12{{CompatGeckoDesktop("42")}}{{CompatIE(11)}}{{CompatVersionUnknown}}9
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatChrome(38)}} [1]{{ CompatGeckoMobile("13") }}{{CompatNo}}{{CompatNo}}8
Constructor argument: new Set(iterable){{CompatNo}}{{CompatChrome(38)}}{{ CompatGeckoMobile("13") }}{{CompatNo}}{{CompatNo}}9
iterable{{CompatNo}}{{CompatNo}}{{ CompatGeckoMobile("17") }}{{CompatNo}}{{CompatNo}}8
Set.clear(){{CompatNo}}{{ CompatChrome(38) }}{{CompatGeckoMobile("19")}}{{CompatNo}}{{CompatNo}}8
Set.keys(), Set.values(), Set.entries(){{CompatNo}}{{ CompatChrome(38) }}{{CompatGeckoMobile("24")}}{{CompatNo}}{{CompatNo}}8
Set.forEach(){{CompatNo}}{{ CompatChrome(38) }}{{CompatGeckoMobile("25")}}{{CompatNo}}{{CompatNo}}8
Value equality for -0 and 0{{CompatNo}}{{ CompatChrome(38) }}{{CompatGeckoMobile("29")}}{{CompatNo}}{{CompatNo}}9
Constructor argument: new Set(null){{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("37")}}{{CompatUnknown}}{{CompatUnknown}}8
Monkey-patched add() in Constructor{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("37")}}{{CompatUnknown}}{{CompatUnknown}}9
Set[@@species]{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("41")}}{{CompatUnknown}}{{CompatUnknown}}10
Set() without new throws{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("42")}}{{CompatUnknown}}{{CompatUnknown}}9
+
+ +

[1] The feature was available behind a preference from Chrome 31. In chrome://flags, activate the entry “Enable Experimental JavaScript”.

+ +

مطالب مرتبط

+ + +
diff --git a/files/fa/web/javascript/reference/index.html b/files/fa/web/javascript/reference/index.html new file mode 100644 index 0000000000..d78299497a --- /dev/null +++ b/files/fa/web/javascript/reference/index.html @@ -0,0 +1,50 @@ +--- +title: مرجع جاوا اسکریپت +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/fa/web/javascript/reference/operators/index.html b/files/fa/web/javascript/reference/operators/index.html new file mode 100644 index 0000000000..636cb3acca --- /dev/null +++ b/files/fa/web/javascript/reference/operators/index.html @@ -0,0 +1,302 @@ +--- +title: Expressions and operators +slug: Web/JavaScript/Reference/Operators +tags: + - بازبینی + - جاوااسکریپت + - عملوند + - منابع +translation_of: Web/JavaScript/Reference/Operators +--- +
{{jsSidebar("Operators")}}
+ +
این بخش از سند شامل تمامی عمل ها و عبارت و کلمات کلیدی بکار رفته در زبان برنامه نویسی جاوااسکریپت می باشد.
+ +

دسته بندی عبارت و عمل ها

+ +

لیست زیر براساس الفابت انگلیسی مرتب شده است

+ +

عبارات اصلی

+ +

عبارت عمومی و کلمات کلیدی اصلی در جاوا اسکریپت.

+ +
+
{{jsxref("Operators/this", "this")}}
+
کلمه کلیدی this به محتوایی در درون تابعی که در آن نوشته شده است اشاره می کند.
+
{{jsxref("Operators/function", "function")}}
+
کلمه کلیدی function  ٫ تعریف کننده یک تابع است.
+
{{jsxref("Operators/class", "class")}}
+
کلمه کلیدی class  ٫ تعریف کننده یک کلاس است.
+
{{jsxref("Operators/function*", "function*")}}
+
کلمه کلیدی function*  تعریف کننده یک سازنده کلاس است.
+
{{jsxref("Operators/yield", "yield")}}
+
مکث و از سرگیری می کند تابعی که تولید شده است.
+
{{jsxref("Operators/yield*", "yield*")}}
+
محول می کند به تابع یا آبجکت تولید شده دیگر.
+
{{experimental_inline}} {{jsxref("Operators/async_function", "async function*")}}
+
async function  یک تابع async تعریف می کند
+
{{experimental_inline}} {{jsxref("Operators/await", "await")}}
+
مکث و از سرگیری می کند و تابع اسینک (async ) و منتظر اجازه  برای تایید را رد می ماند
+
{{jsxref("Global_Objects/Array", "[]")}}
+
تعریف کننده /سازنده یک آرایه .
+
{{jsxref("Operators/Object_initializer", "{}")}}
+
تعریف کننده / سازنده یک آبجکت ( شئی) .
+
{{jsxref("Global_Objects/RegExp", "/ab+c/i")}}
+
یک ترکیب صحیح از عبارتها
+
{{jsxref("Operators/Grouping", "( )")}}
+
دسته بندی عمل ها
+
+ +

عبارت های سمت چپ

+ +

مقدارهای سمت چپ مشخص کردن  هدف هستند 

+ +
+
{{jsxref("Operators/Property_accessors", "Property accessors", "", 1)}}
+
عمل های شامل درستی به یک ویژگی یا متد از یک آبجکت(شئی) از قبل تعریف شده
+ (object.property  و object["property"]).
+
{{jsxref("Operators/new", "new")}}
+
عمل new  یک سازنده از الگو یا موجودیت از قبل تعریف شده مثل آبجکت 
+
new.target
+
In constructors, new.target refers to the constructor that was invoked by {{jsxref("Operators/new", "new")}}.
+
{{jsxref("Operators/super", "super")}}
+
کلیدواژه super  والد سازنده را صدا می زند
+
{{jsxref("Operators/Spread_operator", "...obj")}}
+
The spread operator allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) are expected.
+
+ +

افزایش و کاهش

+ +

عملوند  پیشوندی/ پسوندی افزایشی و  عملوند پیشوندی/پسوندی کاهشی

+ +
+
{{jsxref("Operators/Arithmetic_Operators", "A++", "#Increment")}}
+
عملوند پسوندی افزایشی.
+
{{jsxref("Operators/Arithmetic_Operators", "A--", "#Decrement")}}
+
عملوند پسوندی کاهشی.
+
{{jsxref("Operators/Arithmetic_Operators", "++A", "#Increment")}}
+
عملوند پیشوندی افزایشی.
+
{{jsxref("Operators/Arithmetic_Operators", "--A", "#Decrement")}}
+
عملوند پیشوند کاهشی
+
+ +

عملوند های یکتا

+ +

A unary operation is operation with only one operand.

+ +
+
{{jsxref("Operators/delete", "delete")}}
+
عملوند delete  ویژگی /ها را از یک آبجکت حذف می کند.
+
{{jsxref("Operators/void", "void")}}
+
در عمل کننده void مقداری برای بازگشت از یک عبارت وجود ندارد.
+
{{jsxref("Operators/typeof", "typeof")}}
+
typeof  نوع آبجکت (شئی )دریافتی را مشخص می کند.
+
{{jsxref("Operators/Arithmetic_Operators", "+", "#Unary_plus")}}
+
The unary plus operator converts its operand to Number type.
+
{{jsxref("Operators/Arithmetic_Operators", "-", "#Unary_negation")}}
+
The unary negation operator converts its operand to Number type and then negates it.
+
{{jsxref("Operators/Bitwise_Operators", "~", "#Bitwise_NOT")}}
+
Bitwise NOT operator.
+
{{jsxref("Operators/Logical_Operators", "!", "#Logical_NOT")}}
+
Logical NOT operator.
+
+ +

عملوند های منطقی

+ +

عملوندهای منطقی روی مقدار عددی اعمال می شوند و یک عدد به عنوان نتیجه منطقی  عملوند منطقی خواهد بود

+ +
+
{{jsxref("Operators/Arithmetic_Operators", "+", "#Addition")}}
+
عمل جمع.
+
{{jsxref("Operators/Arithmetic_Operators", "-", "#Subtraction")}}
+
عمل تفریق/منها
+
{{jsxref("Operators/Arithmetic_Operators", "/", "#Division")}}
+
عمل تقسیم
+
{{jsxref("Operators/Arithmetic_Operators", "*", "#Multiplication")}}
+
عمل ضرب
+
{{jsxref("Operators/Arithmetic_Operators", "%", "#Remainder")}}
+
عمل تقسیم / خروجی باقیماند تقسیم
+
+ +
+
{{jsxref("Operators/Arithmetic_Operators", "**", "#Exponentiation")}}
+
عمل توان
+
+ +

Relational operators

+ +

A comparison operator compares its operands and returns a Boolean value based on whether the comparison is true.

+ +
+
{{jsxref("Operators/in", "in")}}
+
The in operator determines whether an object has a given property.
+
{{jsxref("Operators/instanceof", "instanceof")}}
+
The instanceof operator determines whether an object is an instance of another object.
+
{{jsxref("Operators/Comparison_Operators", "<", "#Less_than_operator")}}
+
Less than operator.
+
{{jsxref("Operators/Comparison_Operators", ">", "#Greater_than_operator")}}
+
Greater than operator.
+
{{jsxref("Operators/Comparison_Operators", "<=", "#Less_than_or_equal_operator")}}
+
Less than or equal operator.
+
{{jsxref("Operators/Comparison_Operators", ">=", "#Greater_than_or_equal_operator")}}
+
Greater than or equal operator.
+
+ +
+

Note: => is not an operator, but the notation for Arrow functions.

+
+ +

Equality operators

+ +

The result of evaluating an equality operator is always of type Boolean based on whether the comparison is true.

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

Bitwise shift operators

+ +

Operations to shift all bits of the operand.

+ +
+
{{jsxref("Operators/Bitwise_Operators", "<<", "#Left_shift")}}
+
Bitwise left shift operator.
+
{{jsxref("Operators/Bitwise_Operators", ">>", "#Right_shift")}}
+
Bitwise right shift operator.
+
{{jsxref("Operators/Bitwise_Operators", ">>>", "#Unsigned_right_shift")}}
+
Bitwise unsigned right shift operator.
+
+ +

Binary bitwise operators

+ +

Bitwise operators treat their operands as a set of 32 bits (zeros and ones) and return standard JavaScript numerical values.

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

Binary logical operators

+ +

Logical operators are typically used with boolean (logical) values, and when they are, they return a boolean value.

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

Conditional (ternary) operator

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

The conditional operator returns one of two values based on the logical value of the condition.

+
+
+ +

Assignment operators

+ +

An assignment operator assigns a value to its left operand based on the value of its right operand.

+ +
+
{{jsxref("Operators/Assignment_Operators", "=", "#Assignment")}}
+
Assignment operator.
+
{{jsxref("Operators/Assignment_Operators", "*=", "#Multiplication_assignment")}}
+
Multiplication assignment.
+
{{jsxref("Operators/Assignment_Operators", "/=", "#Division_assignment")}}
+
Division assignment.
+
{{jsxref("Operators/Assignment_Operators", "%=", "#Remainder_assignment")}}
+
Remainder assignment.
+
{{jsxref("Operators/Assignment_Operators", "+=", "#Addition_assignment")}}
+
Addition assignment.
+
{{jsxref("Operators/Assignment_Operators", "-=", "#Subtraction_assignment")}}
+
Subtraction assignment
+
{{jsxref("Operators/Assignment_Operators", "<<=", "#Left_shift_assignment")}}
+
Left shift assignment.
+
{{jsxref("Operators/Assignment_Operators", ">>=", "#Right_shift_assignment")}}
+
Right shift assignment.
+
{{jsxref("Operators/Assignment_Operators", ">>>=", "#Unsigned_right_shift_assignment")}}
+
Unsigned right shift assignment.
+
{{jsxref("Operators/Assignment_Operators", "&=", "#Bitwise_AND_assignment")}}
+
Bitwise AND assignment.
+
{{jsxref("Operators/Assignment_Operators", "^=", "#Bitwise_XOR_assignment")}}
+
Bitwise XOR assignment.
+
{{jsxref("Operators/Assignment_Operators", "|=", "#Bitwise_OR_assignment")}}
+
Bitwise OR assignment.
+
{{jsxref("Operators/Destructuring_assignment", "[a, b] = [1, 2]")}}
+ {{jsxref("Operators/Destructuring_assignment", "{a, b} = {a:1, b:2}")}}
+
+

Destructuring assignment allows you to assign the properties of an array or object to variables using syntax that looks similar to array or object literals.

+
+
+ +

Comma operator

+ +
+
{{jsxref("Operators/Comma_Operator", ",")}}
+
The comma operator allows multiple expressions to be evaluated in a single statement and returns the result of the last expression.
+
+ +

Non-standard features

+ +
+
{{non-standard_inline}} {{jsxref("Operators/Legacy_generator_function", "Legacy generator function", "", 1)}}
+
The function keyword can be used to define a legacy generator function inside an expression. To make the function a legacy generator, the function body should contains at least one {{jsxref("Operators/yield", "yield")}} expression.
+
{{non-standard_inline}} {{jsxref("Operators/Expression_closures", "Expression closures", "", 1)}}
+
The expression closure syntax is a shorthand for writing simple function.
+
{{non-standard_inline}} {{jsxref("Operators/Array_comprehensions", "[for (x of y) x]")}}
+
Array comprehensions.
+
{{non-standard_inline}} {{jsxref("Operators/Generator_comprehensions", "(for (x of y) y)")}}
+
Generator comprehensions.
+
+ +

Specifications

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

See also

+ + diff --git a/files/fa/web/javascript/reference/statements/index.html b/files/fa/web/javascript/reference/statements/index.html new file mode 100644 index 0000000000..368977efc8 --- /dev/null +++ b/files/fa/web/javascript/reference/statements/index.html @@ -0,0 +1,131 @@ +--- +title: Statements and declarations +slug: Web/JavaScript/Reference/Statements +tags: + - JavaScript + - NeedsTranslation + - Reference + - TopicStub + - statements +translation_of: Web/JavaScript/Reference/Statements +--- +
{{jsSidebar("Statements")}}
+ +

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

+ +

Statements and declarations by category

+ +

For an alphabetical listing see the sidebar on the left.

+ +

Control flow

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

Declarations

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

Functions and classes

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

Iterations

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

Others

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

Specifications

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

See also

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