From 95aca4b4d8fa62815d4bd412fff1a364f842814a Mon Sep 17 00:00:00 2001 From: Ryan Johnson Date: Thu, 29 Apr 2021 16:16:42 -0700 Subject: remove retired locales (#699) --- .../web/javascript/data_structures/index.html | 298 --------- .../guide/details_of_the_object_model/index.html | 736 --------------------- .../javascript/guide/grammar_and_types/index.html | 642 ------------------ files/pt-pt/web/javascript/guide/index.html | 124 ---- .../web/javascript/guide/introduction/index.html | 138 ---- files/pt-pt/web/javascript/index.html | 140 ---- .../web/javascript/memory_management/index.html | 188 ------ .../web/javascript/reference/about/index.html | 53 -- .../web/javascript/reference/classes/index.html | 437 ------------ .../javascript/reference/classes/static/index.html | 131 ---- .../deprecated_and_obsolete_features/index.html | 290 -------- .../web/javascript/reference/errors/index.html | 31 - .../reference/errors/not_a_function/index.html | 172 ----- .../reference/errors/stmt_after_return/index.html | 77 --- .../reference/errors/unexpected_token/index.html | 50 -- .../errors/unnamed_function_statement/index.html | 114 ---- .../reference/functions/arguments/index.html | 229 ------- .../reference/functions/arrow_functions/index.html | 400 ----------- .../web/javascript/reference/functions/index.html | 595 ----------------- .../reference/functions/rest_parameters/index.html | 235 ------- .../global_objects/array/concat/index.html | 205 ------ .../reference/global_objects/array/find/index.html | 210 ------ .../global_objects/array/foreach/index.html | 328 --------- .../global_objects/array/includes/index.html | 175 ----- .../reference/global_objects/array/index.html | 440 ------------ .../reference/global_objects/array/join/index.html | 90 --- .../reference/global_objects/array/map/index.html | 366 ---------- .../reference/global_objects/array/pop/index.html | 96 --- .../global_objects/array/reverse/index.html | 133 ---- .../global_objects/array/slice/index.html | 154 ----- .../global_objects/arraybuffer/index.html | 219 ------ .../global_objects/asyncfunction/index.html | 124 ---- .../reference/global_objects/boolean/index.html | 156 ----- .../reference/global_objects/encodeuri/index.html | 152 ----- .../global_objects/function/arguments/index.html | 88 --- .../global_objects/function/call/index.html | 164 ----- .../reference/global_objects/function/index.html | 192 ------ .../javascript/reference/global_objects/index.html | 173 ----- .../reference/global_objects/infinity/index.html | 69 -- .../reference/global_objects/math/ceil/index.html | 161 ----- .../reference/global_objects/math/index.html | 214 ------ .../reference/global_objects/number/index.html | 213 ------ .../global_objects/number/isfinite/index.html | 126 ---- .../global_objects/number/isinteger/index.html | 125 ---- .../global_objects/number/isnan/index.html | 136 ---- .../global_objects/number/max_value/index.html | 119 ---- .../global_objects/number/min_value/index.html | 121 ---- .../reference/global_objects/number/nan/index.html | 103 --- .../number/negative_infinity/index.html | 91 --- .../global_objects/number/tostring/index.html | 146 ---- .../object/hasownproperty/index.html | 187 ------ .../reference/global_objects/object/index.html | 184 ------ .../reference/global_objects/string/index.html | 326 --------- .../global_objects/string/indexof/index.html | 191 ------ .../global_objects/string/length/index.html | 125 ---- .../global_objects/string/trim/index.html | 139 ---- .../global_objects/symbol/hasinstance/index.html | 114 ---- .../reference/global_objects/symbol/index.html | 458 ------------- files/pt-pt/web/javascript/reference/index.html | 307 --------- .../reference/operators/comma_operator/index.html | 95 --- .../reference/operators/function/index.html | 140 ---- .../web/javascript/reference/operators/index.html | 310 --------- .../operators/operator_precedence/index.html | 462 ------------- .../reference/statements/block/index.html | 117 ---- .../javascript/reference/statements/for/index.html | 146 ---- .../web/javascript/reference/statements/index.html | 151 ----- .../reference/statements/return/index.html | 149 ----- .../reference/statements/throw/index.html | 272 -------- files/pt-pt/web/javascript/shells/index.html | 30 - 69 files changed, 14072 deletions(-) delete mode 100644 files/pt-pt/web/javascript/data_structures/index.html delete mode 100644 files/pt-pt/web/javascript/guide/details_of_the_object_model/index.html delete mode 100644 files/pt-pt/web/javascript/guide/grammar_and_types/index.html delete mode 100644 files/pt-pt/web/javascript/guide/index.html delete mode 100644 files/pt-pt/web/javascript/guide/introduction/index.html delete mode 100644 files/pt-pt/web/javascript/index.html delete mode 100644 files/pt-pt/web/javascript/memory_management/index.html delete mode 100644 files/pt-pt/web/javascript/reference/about/index.html delete mode 100644 files/pt-pt/web/javascript/reference/classes/index.html delete mode 100644 files/pt-pt/web/javascript/reference/classes/static/index.html delete mode 100644 files/pt-pt/web/javascript/reference/deprecated_and_obsolete_features/index.html delete mode 100644 files/pt-pt/web/javascript/reference/errors/index.html delete mode 100644 files/pt-pt/web/javascript/reference/errors/not_a_function/index.html delete mode 100644 files/pt-pt/web/javascript/reference/errors/stmt_after_return/index.html delete mode 100644 files/pt-pt/web/javascript/reference/errors/unexpected_token/index.html delete mode 100644 files/pt-pt/web/javascript/reference/errors/unnamed_function_statement/index.html delete mode 100644 files/pt-pt/web/javascript/reference/functions/arguments/index.html delete mode 100644 files/pt-pt/web/javascript/reference/functions/arrow_functions/index.html delete mode 100644 files/pt-pt/web/javascript/reference/functions/index.html delete mode 100644 files/pt-pt/web/javascript/reference/functions/rest_parameters/index.html delete mode 100644 files/pt-pt/web/javascript/reference/global_objects/array/concat/index.html delete mode 100644 files/pt-pt/web/javascript/reference/global_objects/array/find/index.html delete mode 100644 files/pt-pt/web/javascript/reference/global_objects/array/foreach/index.html delete mode 100644 files/pt-pt/web/javascript/reference/global_objects/array/includes/index.html delete mode 100644 files/pt-pt/web/javascript/reference/global_objects/array/index.html delete mode 100644 files/pt-pt/web/javascript/reference/global_objects/array/join/index.html delete mode 100644 files/pt-pt/web/javascript/reference/global_objects/array/map/index.html delete mode 100644 files/pt-pt/web/javascript/reference/global_objects/array/pop/index.html delete mode 100644 files/pt-pt/web/javascript/reference/global_objects/array/reverse/index.html delete mode 100644 files/pt-pt/web/javascript/reference/global_objects/array/slice/index.html delete mode 100644 files/pt-pt/web/javascript/reference/global_objects/arraybuffer/index.html delete mode 100644 files/pt-pt/web/javascript/reference/global_objects/asyncfunction/index.html delete mode 100644 files/pt-pt/web/javascript/reference/global_objects/boolean/index.html delete mode 100644 files/pt-pt/web/javascript/reference/global_objects/encodeuri/index.html delete mode 100644 files/pt-pt/web/javascript/reference/global_objects/function/arguments/index.html delete mode 100644 files/pt-pt/web/javascript/reference/global_objects/function/call/index.html delete mode 100644 files/pt-pt/web/javascript/reference/global_objects/function/index.html delete mode 100644 files/pt-pt/web/javascript/reference/global_objects/index.html delete mode 100644 files/pt-pt/web/javascript/reference/global_objects/infinity/index.html delete mode 100644 files/pt-pt/web/javascript/reference/global_objects/math/ceil/index.html delete mode 100644 files/pt-pt/web/javascript/reference/global_objects/math/index.html delete mode 100644 files/pt-pt/web/javascript/reference/global_objects/number/index.html delete mode 100644 files/pt-pt/web/javascript/reference/global_objects/number/isfinite/index.html delete mode 100644 files/pt-pt/web/javascript/reference/global_objects/number/isinteger/index.html delete mode 100644 files/pt-pt/web/javascript/reference/global_objects/number/isnan/index.html delete mode 100644 files/pt-pt/web/javascript/reference/global_objects/number/max_value/index.html delete mode 100644 files/pt-pt/web/javascript/reference/global_objects/number/min_value/index.html delete mode 100644 files/pt-pt/web/javascript/reference/global_objects/number/nan/index.html delete mode 100644 files/pt-pt/web/javascript/reference/global_objects/number/negative_infinity/index.html delete mode 100644 files/pt-pt/web/javascript/reference/global_objects/number/tostring/index.html delete mode 100644 files/pt-pt/web/javascript/reference/global_objects/object/hasownproperty/index.html delete mode 100644 files/pt-pt/web/javascript/reference/global_objects/object/index.html delete mode 100644 files/pt-pt/web/javascript/reference/global_objects/string/index.html delete mode 100644 files/pt-pt/web/javascript/reference/global_objects/string/indexof/index.html delete mode 100644 files/pt-pt/web/javascript/reference/global_objects/string/length/index.html delete mode 100644 files/pt-pt/web/javascript/reference/global_objects/string/trim/index.html delete mode 100644 files/pt-pt/web/javascript/reference/global_objects/symbol/hasinstance/index.html delete mode 100644 files/pt-pt/web/javascript/reference/global_objects/symbol/index.html delete mode 100644 files/pt-pt/web/javascript/reference/index.html delete mode 100644 files/pt-pt/web/javascript/reference/operators/comma_operator/index.html delete mode 100644 files/pt-pt/web/javascript/reference/operators/function/index.html delete mode 100644 files/pt-pt/web/javascript/reference/operators/index.html delete mode 100644 files/pt-pt/web/javascript/reference/operators/operator_precedence/index.html delete mode 100644 files/pt-pt/web/javascript/reference/statements/block/index.html delete mode 100644 files/pt-pt/web/javascript/reference/statements/for/index.html delete mode 100644 files/pt-pt/web/javascript/reference/statements/index.html delete mode 100644 files/pt-pt/web/javascript/reference/statements/return/index.html delete mode 100644 files/pt-pt/web/javascript/reference/statements/throw/index.html delete mode 100644 files/pt-pt/web/javascript/shells/index.html (limited to 'files/pt-pt/web/javascript') diff --git a/files/pt-pt/web/javascript/data_structures/index.html b/files/pt-pt/web/javascript/data_structures/index.html deleted file mode 100644 index bdefa55efe..0000000000 --- a/files/pt-pt/web/javascript/data_structures/index.html +++ /dev/null @@ -1,298 +0,0 @@ ---- -title: Tipos de dados de JavaScript e estruturas de dados -slug: Web/JavaScript/Data_structures -tags: - - JavaScript - - Principiante - - Tipos -translation_of: Web/JavaScript/Data_structures -original_slug: Web/JavaScript/Estruturas_de_dados ---- -
{{jsSidebar("More")}}
- -

Programming languages all have built-in data structures, but these often differ from one language to another. This article attempts to list the built-in data structures available in JavaScript and what properties they have; these can be used to build other data structures. When possible, comparisons with other languages are drawn.

- -

Digitação dinâmica

- -

JavaScript is a loosely typed or a dynamic language. Variables in JavaScript are not directly associated with any particular value type, and any variable can be assigned (and re-assigned)  values of all types:

- -
var foo = 42;    // foo is now a Number
-var foo = 'bar'; // foo is now a String
-var foo = true;  // foo is now a Boolean
-
- -

Tipos de dados

- -

The latest ECMAScript standard defines seven data types:

- - - -

Valores primitivos

- -

All types except objects define immutable values (values, which are incapable of being changed). For example and unlike to C, Strings are immutable. We refer to values of these types as "primitive values".

- -

Tipo booleano

- -

Boolean represents a logical entity and can have two values: true, and false.

- -

Tipo Null

- -

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

- -

Tipo indefinido

- -

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

- -

Tipo número

- -

According to the ECMAScript standard, there is only one number type: the double-precision 64-bit binary format IEEE 754 value (number between -(253 -1) and 253 -1). There is no specific type for integers. In addition to being able to represent floating-point numbers, the number type has three symbolic values: +Infinity, -Infinity, and NaN (not-a-number).

- -

To check for the largest available value or smallest available value within +/-Infinity, you can use the constants {{jsxref("Number.MAX_VALUE")}} or {{jsxref("Number.MIN_VALUE")}} and starting with ECMAScript 6, you are also able to check if a number is in the double-precision floating-point number range using {{jsxref("Number.isSafeInteger()")}} as well as {{jsxref("Number.MAX_SAFE_INTEGER")}} and {{jsxref("Number.MIN_SAFE_INTEGER")}}. Beyond this range, integers in JavaScript are not safe anymore and will be a double-precision floating point approximation of the value.

- -

The number type has only one integer that has two representations: 0 is represented as -0 and +0. ("0" is an alias for +0). In the praxis, this has almost no impact. For example +0 === -0 is true. However, you are able to notice this when you divide by zero:

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

Although a number often represents only its value, JavaScript provides some binary operators. These can be used to represent several Boolean values within a single number using bit masking. However, this is usually considered a bad practice, since JavaScript offers other means to represent a set of Booleans (like an array of Booleans or an object with Boolean values assigned to named properties). Bit masking also tends to make code more difficult to read, understand, and maintain. It may be necessary to use such techniques in very constrained environments, like when trying to cope with the storage limitation of local storage or in extreme cases when each bit over the network counts. This technique should only be considered when it is the last measure that can be taken to optimize size.

- -

Tipo string

- -

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

- -

Unlike in languages like C, JavaScript strings are immutable. This means that once a string is created, it is not possible to modify it. However, it is still possible to create another string based on an operation on the original string. For example:

- - - -

Beware of "stringly-typing" your code!

- -

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

- - - -

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

- -

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

- -

Tipo símbolo

- -

Symbols are new to JavaScript in ECMAScript Edition 6. A Symbol is a unique and immutable primitive value and may be used as the key of an Object property (see below). In some programming languages, Symbols are called atoms. For more details see {{Glossary("Symbol")}} and the {{jsxref("Symbol")}} object wrapper in JavaScript.

- -

Objetos

- -

In computer science, an object is a value in memory which is possibly referenced by an {{Glossary("Identifier", "identifier")}}.

- -

Propriedades

- -

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

- -

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

- -

Data property

- -

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

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Attributes of a data property
AttributeTypeDescriptionDefault value
[[Value]]Any JavaScript typeThe value retrieved by a get access of the property.undefined
[[Writable]]BooleanIf false, the property's [[Value]] can't be changed.false
[[Enumerable]]BooleanIf true, the property will be enumerated in for...in loops. See also Enumerability and ownership of propertiesfalse
[[Configurable]]BooleanIf false, the property can't be deleted and attributes other than [[Value]] and [[Writable]] can't be changed.false
- - - - - - - - - - - - - - - - - - - - - - - - - -
Obsolete attributes (as of ECMAScript 3, renamed in ECMAScript 5)
AttributeTypeDescription
Read-onlyBooleanReversed state of the ES5 [[Writable]] attribute.
DontEnumBooleanReversed state of the ES5 [[Enumerable]] attribute.
DontDeleteBooleanReversed state of the ES5 [[Configurable]] attribute.
- -

Accessor property

- -

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

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

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

-
- -

Objetos "Normal", e funções

- -

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

- -

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

- -

Dates

- -

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

- -

Coleções indexadas: Arrays e Arrays digitados

- -

Arrays are regular objects for which there is a particular relationship between integer-key-ed properties and the 'length' property. Additionally, arrays inherit from Array.prototype which provides to them a handful of convenient methods to manipulate arrays. For example, indexOf (searching a value in the array) or push (adding an element to the array), etc. This makes Arrays a perfect candidate to represent lists or sets.

- -

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

- -

{{page("/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray", "TypedArray_objects", "", 0, 3)}}

- -

Keyed collections: Maps, Sets, WeakMaps, WeakSets

- -

These data structures take object references as keys and are introduced in ECMAScript Edition 6. {{jsxref("Set")}} and {{jsxref("WeakSet")}} represent a set of objects, while {{jsxref("Map")}} and {{jsxref("WeakMap")}} associate a value to an object. The difference between Maps and WeakMaps is that in the former, object keys can be enumerated over. This allows garbage collection optimizations in the latter case.

- -

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

- -

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

- -

Structured data: JSON

- -

JSON (JavaScript Object Notation) is a lightweight data-interchange format, derived from JavaScript but used by many programming languages. JSON builds universal data structures. See {{Glossary("JSON")}} and {{jsxref("JSON")}} for more details.

- -

More objects in the standard library

- -

JavaScript has a standard library of built-in objects. Please have a look at the reference to find out about more objects.

- -

Determining types using the typeof operator

- -

The typeof operator can help you to find the type of your variable. Please read the reference page for more details and edge cases.

- -

Especificações

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition.
{{SpecName('ES5.1', '#sec-8', 'Types')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-ecmascript-data-types-and-values', 'ECMAScript Data Types and Values')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-ecmascript-data-types-and-values', 'ECMAScript Data Types and Values')}}{{Spec2('ESDraft')}} 
- -

Consulte também

- - diff --git a/files/pt-pt/web/javascript/guide/details_of_the_object_model/index.html b/files/pt-pt/web/javascript/guide/details_of_the_object_model/index.html deleted file mode 100644 index 4f8afaf09a..0000000000 --- a/files/pt-pt/web/javascript/guide/details_of_the_object_model/index.html +++ /dev/null @@ -1,736 +0,0 @@ ---- -title: Detalhes do modelo de objeto -slug: Web/JavaScript/Guide/Details_of_the_Object_Model -tags: - - Guia(2) - - Intermediário - - JavaScript - - Objeto -translation_of: Web/JavaScript/Guide/Details_of_the_Object_Model -original_slug: Web/JavaScript/Guia/Detalhes_do_modelo_de_objeto ---- -
{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Working_with_Objects", "Web/JavaScript/Guide/Iterators_and_Generators")}}
- -
-

The content of this article is under discussion. Please provide feedback and help us to make this page better: {{bug(1201380)}}.

-
- -

JavaScript is an object-based language based on prototypes, rather than being class-based. Because of this different basis, it can be less apparent how JavaScript allows you to create hierarchies of objects and to have inheritance of properties and their values. This chapter attempts to clarify the situation.

- -

This chapter assumes that you are already somewhat familiar with JavaScript and that you have used JavaScript functions to create simple objects.

- -

Linguagens com base em classe versus protótipo

- -

Class-based object-oriented languages, such as Java and C++, are founded on the concept of two distinct entities: classes and instances.

- - - -

A prototype-based language, such as JavaScript, does not make this distinction: it simply has objects. A prototype-based language has the notion of a prototypical object, an object used as a template from which to get the initial properties for a new object. Any object can specify its own properties, either when you create it or at run time. In addition, any object can be associated as the prototype for another object, allowing the second object to share the first object's properties.

- -

Definição de uma classe

- -

In class-based languages, you define a class in a separate class definition. In that definition you can specify special methods, called constructors, to create instances of the class. A constructor method can specify initial values for the instance's properties and perform other processing appropriate at creation time. You use the new operator in association with the constructor method to create class instances.

- -

JavaScript follows a similar model, but does not have a class definition separate from the constructor. Instead, you define a constructor function to create objects with a particular initial set of properties and values. Any JavaScript function can be used as a constructor. You use the new operator with a constructor function to create a new object.

- -

Subclasses e sucessão

- -

In a class-based language, you create a hierarchy of classes through the class definitions. In a class definition, you can specify that the new class is a subclass of an already existing class. The subclass inherits all the properties of the superclass and additionally can add new properties or modify the inherited ones. For example, assume the Employee class includes only the name and dept properties, and Manager is a subclass of Employee that adds the reports property. In this case, an instance of the Manager class would have all three properties: name, dept, and reports.

- -

JavaScript implements inheritance by allowing you to associate a prototypical object with any constructor function. So, you can create exactly the EmployeeManager example, but you use slightly different terminology. First you define the Employee constructor function, specifying the name and dept properties. Next, you define the Manager constructor function, calling the Employee constructor and specifying the reports property. Finally, you assign a new object derived from Employee.prototype as the prototype for the Manager constructor function. Then, when you create a new Manager, it inherits the name and dept properties from the Employee object.

- -

Adição e remoção de propriedades

- -

In class-based languages, you typically create a class at compile time and then you instantiate instances of the class either at compile time or at run time. You cannot change the number or the type of properties of a class after you define the class. In JavaScript, however, at run time you can add or remove properties of any object. If you add a property to an object that is used as the prototype for a set of objects, the objects for which it is the prototype also get the new property.

- -

Resumo das diferenças

- -

The following table gives a short summary of some of these differences. The rest of this chapter describes the details of using JavaScript constructors and prototypes to create an object hierarchy and compares this to how you would do it in Java.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Comparison of class-based (Java) and prototype-based (JavaScript) object systems
Com base em Classe (Java)Com base em Protótipo (JavaScript)
Class and instance are distinct entities.All objects can inherit from another object.
Define a class with a class definition; instantiate a class with constructor methods.Define and create a set of objects with constructor functions.
Create a single object with the new operator.Same.
Construct an object hierarchy by using class definitions to define subclasses of existing classes.Construct an object hierarchy by assigning an object as the prototype associated with a constructor function.
Inherit properties by following the class chain.Inherit properties by following the prototype chain.
Class definition specifies all properties of all instances of a class. Cannot add properties dynamically at run time.Constructor function or prototype specifies an initial set of properties. Can add or remove properties dynamically to individual objects or to the entire set of objects.
- -

The employee example

- -

The remainder of this chapter uses the employee hierarchy shown in the following figure.

- -
-
-

A simple object hierarchy with the following objects:

- -

-
- -
-
    -
  • Employee has the properties name (whose value defaults to the empty string) and dept (whose value defaults to "general").
  • -
  • Manager is based on Employee. It adds the reports property (whose value defaults to an empty array, intended to have an array of Employee objects as its value).
  • -
  • WorkerBee is also based on Employee. It adds the projects property (whose value defaults to an empty array, intended to have an array of strings as its value).
  • -
  • SalesPerson is based on WorkerBee. It adds the quota property (whose value defaults to 100). It also overrides the dept property with the value "sales", indicating that all salespersons are in the same department.
  • -
  • Engineer is based on WorkerBee. It adds the machine property (whose value defaults to the empty string) and also overrides the dept property with the value "engineering".
  • -
-
-
- -

Criação de hierarquia

- -

There are several ways to define appropriate constructor functions to implement the Employee hierarchy. How you choose to define them depends largely on what you want to be able to do in your application.

- -

This section shows how to use very simple (and comparatively inflexible) definitions to demonstrate how to get the inheritance to work. In these definitions, you cannot specify any property values when you create an object. The newly-created object simply gets the default values, which you can change at a later time.

- -

In a real application, you would probably define constructors that allow you to provide property values at object creation time (see More flexible constructors for information). For now, these simple definitions demonstrate how the inheritance occurs.

- -

The following Java and JavaScript Employee definitions are similar. The only difference is that you need to specify the type for each property in Java but not in JavaScript (this is due to Java being a strongly typed language while JavaScript is a weakly typed language).

- -
-

JavaScript

- -
function Employee() {
-  this.name = "";
-  this.dept = "general";
-}
-
- -

Java

- -
public class Employee {
-   public String name = "";
-   public String dept = "general";
-}
-
-
- -

The Manager and WorkerBee definitions show the difference in how to specify the next object higher in the inheritance chain. In JavaScript, you add a prototypical instance as the value of the prototype property of the constructor function. You can do so at any time after you define the constructor. In Java, you specify the superclass within the class definition. You cannot change the superclass outside the class definition.

- -
-

JavaScript

- -
function Manager() {
-  Employee.call(this);
-  this.reports = [];
-}
-Manager.prototype = Object.create(Employee.prototype);
-
-function WorkerBee() {
-  Employee.call(this);
-  this.projects = [];
-}
-WorkerBee.prototype = Object.create(Employee.prototype);
-
- -

Java

- -
public class Manager extends Employee {
-   public Employee[] reports = new Employee[0];
-}
-
-
-
-public class WorkerBee extends Employee {
-   public String[] projects = new String[0];
-}
-
-
-
-
- -

The Engineer and SalesPerson definitions create objects that descend from WorkerBee and hence from Employee. An object of these types has properties of all the objects above it in the chain. In addition, these definitions override the inherited value of the dept property with new values specific to these objects.

- -
-

JavaScript

- -
function SalesPerson() {
-   WorkerBee.call(this);
-   this.dept = "sales";
-   this.quota = 100;
-}
-SalesPerson.prototype = Object.create(WorkerBee.prototype);
-
-function Engineer() {
-   WorkerBee.call(this);
-   this.dept = "engineering";
-   this.machine = "";
-}
-Engineer.prototype = Object.create(WorkerBee.prototype);
-
- -

Java

- -
public class SalesPerson extends WorkerBee {
-   public double quota;
-   public dept = "sales";
-   public quota = 100.0;
-}
-
-
-public class Engineer extends WorkerBee {
-   public String machine;
-   public dept = "engineering";
-   public machine = "";
-}
-
-
-
- -

Using these definitions, you can create instances of these objects that get the default values for their properties. The next figure illustrates using these JavaScript definitions to create new objects and shows the property values for the new objects.

- -
-

Nota: The term instance has a specific technical meaning in class-based languages. In these languages, an instance is an individual instantiation of a class and is fundamentally different from a class. In JavaScript, "instance" does not have this technical meaning because JavaScript does not have this difference between classes and instances. However, in talking about JavaScript, "instance" can be used informally to mean an object created using a particular constructor function. So, in this example, you could informally say that jane is an instance of Engineer. Similarly, although the terms parent, child, ancestor, and descendant do not have formal meanings in JavaScript; you can use them informally to refer to objects higher or lower in the prototype chain.

-
- -

Criação de objetos com definições simples

- -
-

Hierarquia do objeto

- -

The following hierarchy is created using the code on the right side.

- -

- -

 

- -

individual objects

- -
var jim = new Employee;
-// jim.name is ''
-// jim.dept is 'general'
-
-var sally = new Manager;
-// sally.name is ''
-// sally.dept is 'general'
-// sally.reports is []
-
-var mark = new WorkerBee;
-// mark.name is ''
-// mark.dept is 'general'
-// mark.projects is []
-
-var fred = new SalesPerson;
-// fred.name is ''
-// fred.dept is 'sales'
-// fred.projects is []
-// fred.quota is 100
-
-var jane = new Engineer;
-// jane.name is ''
-// jane.dept is 'engineering'
-// jane.projects is []
-// jane.machine is ''
-
-
- -

Propriedades do objeto

- -

This section discusses how objects inherit properties from other objects in the prototype chain and what happens when you add a property at run time.

- -

Propriedades de sucessão

- -

Suppose you create the mark object as a WorkerBee with the following statement:

- -
var mark = new WorkerBee;
-
- -

When JavaScript sees the new operator, it creates a new generic object and passes this new object as the value of the this keyword to the WorkerBee constructor function. The constructor function explicitly sets the value of the projects property, and implicitly sets the value of the internal __proto__ property to the value of WorkerBee.prototype. (That property name has two underscore characters at the front and two at the end.) The __proto__ property determines the prototype chain used to return property values. Once these properties are set, JavaScript returns the new object and the assignment statement sets the variable mark to that object.

- -

This process does not explicitly put values in the mark object (local values) for the properties that mark inherits from the prototype chain. When you ask for the value of a property, JavaScript first checks to see if the value exists in that object. If it does, that value is returned. If the value is not there locally, JavaScript checks the prototype chain (using the __proto__ property). If an object in the prototype chain has a value for the property, that value is returned. If no such property is found, JavaScript says the object does not have the property. In this way, the mark object has the following properties and values:

- -
mark.name = "";
-mark.dept = "general";
-mark.projects = [];
-
- -

The mark object inherits values for the name and dept properties from the prototypical object in mark.__proto__. It is assigned a local value for the projects property by the WorkerBee constructor. This gives you inheritance of properties and their values in JavaScript. Some subtleties of this process are discussed in Property inheritance revisited.

- -

Because these constructors do not let you supply instance-specific values, this information is generic. The property values are the default ones shared by all new objects created from WorkerBee. You can, of course, change the values of any of these properties. So, you could give specific information for mark as follows:

- -
mark.name = "Doe, Mark";
-mark.dept = "admin";
-mark.projects = ["navigator"];
- -

Adição de propriedades

- -

In JavaScript, you can add properties to any object at run time. You are not constrained to use only the properties provided by the constructor function. To add a property that is specific to a single object, you assign a value to the object, as follows:

- -
mark.bonus = 3000;
-
- -

Now, the mark object has a bonus property, but no other WorkerBee has this property.

- -

If you add a new property to an object that is being used as the prototype for a constructor function, you add that property to all objects that inherit properties from the prototype. For example, you can add a specialty property to all employees with the following statement:

- -
Employee.prototype.specialty = "none";
-
- -

As soon as JavaScript executes this statement, the mark object also has the specialty property with the value of "none". The following figure shows the effect of adding this property to the Employee prototype and then overriding it for the Engineer prototype.

- -


- Adding properties

- -

Mais construtores flexíveis

- -

The constructor functions shown so far do not let you specify property values when you create an instance. As with Java, you can provide arguments to constructors to initialize property values for instances. The following figure shows one way to do this.

- -


- Specifying properties in a constructor, take 1

- -

The following table shows the Java and JavaScript definitions for these objects.

- -
-

JavaScript

- -

Java

-
- -
-
function Employee (name, dept) {
-  this.name = name || "";
-  this.dept = dept || "general";
-}
-
- -

 

- -

 

- -

 

- -

 

- -

 

- -
public class Employee {
-   public String name;
-   public String dept;
-   public Employee () {
-      this("", "general");
-   }
-   public Employee (String name) {
-      this(name, "general");
-   }
-   public Employee (String name, String dept) {
-      this.name = name;
-      this.dept = dept;
-   }
-}
-
-
- -
-
function WorkerBee (projs) {
-
- this.projects = projs || [];
-}
-WorkerBee.prototype = new Employee;
-
- -

 

- -

 

- -

 

- -
public class WorkerBee extends Employee {
-   public String[] projects;
-   public WorkerBee () {
-      this(new String[0]);
-   }
-   public WorkerBee (String[] projs) {
-      projects = projs;
-   }
-}
-
-
- -
-
-function Engineer (mach) {
-   this.dept = "engineering";
-   this.machine = mach || "";
-}
-Engineer.prototype = new WorkerBee;
-
- -

 

- -

 

- -

 

- -
public class Engineer extends WorkerBee {
-   public String machine;
-   public Engineer () {
-      dept = "engineering";
-      machine = "";
-   }
-   public Engineer (String mach) {
-      dept = "engineering";
-      machine = mach;
-   }
-}
-
-
- -

These JavaScript definitions use a special idiom for setting default values:

- -
this.name = name || "";
-
- -

The JavaScript logical OR operator (||) evaluates its first argument. If that argument converts to true, the operator returns it. Otherwise, the operator returns the value of the second argument. Therefore, this line of code tests to see if name has a useful value for the name property. If it does, it sets this.name to that value. Otherwise, it sets this.name to the empty string. This chapter uses this idiom for brevity; however, it can be puzzling at first glance.

- -
-

Note: This may not work as expected if the constructor function is called with arguments which convert to false (like 0 (zero) and empty string (""). In this case the default value will be chosen.

-
- -

With these definitions, when you create an instance of an object, you can specify values for the locally defined properties. You can use the following statement to create a new Engineer:

- -
var jane = new Engineer("belau");
-
- -

Jane's properties are now:

- -
jane.name == "";
-jane.dept == "engineering";
-jane.projects == [];
-jane.machine == "belau"
-
- -

Notice that with these definitions, you cannot specify an initial value for an inherited property such as name. If you want to specify an initial value for inherited properties in JavaScript, you need to add more code to the constructor function.

- -

So far, the constructor function has created a generic object and then specified local properties and values for the new object. You can have the constructor add more properties by directly calling the constructor function for an object higher in the prototype chain. The following figure shows these new definitions.

- -


- Specifying properties in a constructor, take 2

- -

Let's look at one of these definitions in detail. Here's the new definition for the Engineer constructor:

- -
function Engineer (name, projs, mach) {
-  this.base = WorkerBee;
-  this.base(name, "engineering", projs);
-  this.machine = mach || "";
-}
-
- -

Suppose you create a new Engineer object as follows:

- -
var jane = new Engineer("Doe, Jane", ["navigator", "javascript"], "belau");
-
- -

JavaScript follows these steps:

- -
    -
  1. The new operator creates a generic object and sets its __proto__ property to Engineer.prototype.
  2. -
  3. The new operator passes the new object to the Engineer constructor as the value of the this keyword.
  4. -
  5. The constructor creates a new property called base for that object and assigns the value of the WorkerBee constructor to the base property. This makes the WorkerBee constructor a method of the Engineer object.The name of the base property is not special. You can use any legal property name; base is simply evocative of its purpose.
  6. -
  7. -

    The constructor calls the base method, passing as its arguments two of the arguments passed to the constructor ("Doe, Jane" and ["navigator", "javascript"]) and also the string "engineering". Explicitly using "engineering" in the constructor indicates that all Engineer objects have the same value for the inherited dept property, and this value overrides the value inherited from Employee.

    -
  8. -
  9. Because base is a method of Engineer, within the call to base, JavaScript binds the this keyword to the object created in Step 1. Thus, the WorkerBee function in turn passes the "Doe, Jane" and "engineering" arguments to the Employee constructor function. Upon return from the Employee constructor function, the WorkerBee function uses the remaining argument to set the projects property.
  10. -
  11. Upon return from the base method, the Engineer constructor initializes the object's machine property to "belau".
  12. -
  13. Upon return from the constructor, JavaScript assigns the new object to the jane variable.
  14. -
- -

You might think that, having called the WorkerBee constructor from inside the Engineer constructor, you have set up inheritance appropriately for Engineer objects. This is not the case. Calling the WorkerBee constructor ensures that an Engineer object starts out with the properties specified in all constructor functions that are called. However, if you later add properties to the Employee or WorkerBee prototypes, those properties are not inherited by the Engineer object. For example, assume you have the following statements:

- -
function Engineer (name, projs, mach) {
-  this.base = WorkerBee;
-  this.base(name, "engineering", projs);
-  this.machine = mach || "";
-}
-var jane = new Engineer("Doe, Jane", ["navigator", "javascript"], "belau");
-Employee.prototype.specialty = "none";
-
- -

The jane object does not inherit the specialty property. You still need to explicitly set up the prototype to ensure dynamic inheritance. Assume instead you have these statements:

- -
function Engineer (name, projs, mach) {
-  this.base = WorkerBee;
-  this.base(name, "engineering", projs);
-  this.machine = mach || "";
-}
-Engineer.prototype = new WorkerBee;
-var jane = new Engineer("Doe, Jane", ["navigator", "javascript"], "belau");
-Employee.prototype.specialty = "none";
-
- -

Now the value of the jane object's specialty property is "none".

- -

Another way of inheriting is by using the call() / apply() methods. Below are equivalent:

- -
-
function Engineer (name, projs, mach) {
-  this.base = WorkerBee;
-  this.base(name, "engineering", projs);
-  this.machine = mach || "";
-}
-
- -
function Engineer (name, projs, mach) {
-  WorkerBee.call(this, name, "engineering", projs);
-  this.machine = mach || "";
-}
-
-
- -

Using the javascript call() method makes a cleaner implementation because the base is not needed anymore.

- -

Sucessão de propriedade revisitada

- -

The preceding sections described how JavaScript constructors and prototypes provide hierarchies and inheritance. This section discusses some subtleties that were not necessarily apparent in the earlier discussions.

- -

Valores locais versus sucedidos

- -

When you access an object property, JavaScript performs these steps, as described earlier in this chapter:

- -
    -
  1. Check to see if the value exists locally. If it does, return that value.
  2. -
  3. If there is not a local value, check the prototype chain (using the __proto__ property).
  4. -
  5. If an object in the prototype chain has a value for the specified property, return that value.
  6. -
  7. If no such property is found, the object does not have the property.
  8. -
- -

The outcome of these steps depends on how you define things along the way. The original example had these definitions:

- -
function Employee () {
-  this.name = "";
-  this.dept = "general";
-}
-
-function WorkerBee () {
-  this.projects = [];
-}
-WorkerBee.prototype = new Employee;
-
- -

With these definitions, suppose you create amy as an instance of WorkerBee with the following statement:

- -
var amy = new WorkerBee;
-
- -

The amy object has one local property, projects. The values for the name and dept properties are not local to amy and so derive from the amy object's __proto__ property. Thus, amy has these property values:

- -
amy.name == "";
-amy.dept == "general";
-amy.projects == [];
-
- -

Now suppose you change the value of the name property in the prototype associated with Employee:

- -
Employee.prototype.name = "Unknown"
-
- -

At first glance, you might expect that new value to propagate down to all the instances of Employee. However, it does not.

- -

When you create any instance of the Employee object, that instance gets a local value for the name property (the empty string). This means that when you set the WorkerBee prototype by creating a new Employee object, WorkerBee.prototype has a local value for the name property. Therefore, when JavaScript looks up the name property of the amy object (an instance of WorkerBee), JavaScript finds the local value for that property in WorkerBee.prototype. It therefore does not look further up the chain to Employee.prototype.

- -

If you want to change the value of an object property at run time and have the new value be inherited by all descendants of the object, you cannot define the property in the object's constructor function. Instead, you add it to the constructor's associated prototype. For example, assume you change the preceding code to the following:

- -
function Employee () {
-  this.dept = "general";
-}
-Employee.prototype.name = "";
-
-function WorkerBee () {
-  this.projects = [];
-}
-WorkerBee.prototype = new Employee;
-
-var amy = new WorkerBee;
-
-Employee.prototype.name = "Unknown";
-
- -

In this case, the name property of amy becomes "Unknown".

- -

As these examples show, if you want to have default values for object properties and you want to be able to change the default values at run time, you should set the properties in the constructor's prototype, not in the constructor function itself.

- -

Determining instance relationships

- -

Property lookup in JavaScript looks within an object's own properties and, if the property name is not found, it looks within the special object property __proto__. This continues recursively; the process is called "lookup in the prototype chain".

- -

The special property __proto__ is set when an object is constructed; it is set to the value of the constructor's prototype property. So the expression new Foo() creates an object with __proto__ == Foo.prototype. Consequently, changes to the properties of Foo.prototype alters the property lookup for all objects that were created by new Foo().

- -

Every object has a __proto__ object property (except Object); every function has a prototype object property. So objects can be related by 'prototype inheritance' to other objects. You can test for inheritance by comparing an object's __proto__ to a function's prototype object. JavaScript provides a shortcut: the instanceof operator tests an object against a function and returns true if the object inherits from the function prototype. For example,

- -
var f = new Foo();
-var isTrue = (f instanceof Foo);
- -

For a more detailed example, suppose you have the same set of definitions shown in Inheriting properties. Create an Engineer object as follows:

- -
var chris = new Engineer("Pigman, Chris", ["jsd"], "fiji");
-
- -

With this object, the following statements are all true:

- -
chris.__proto__ == Engineer.prototype;
-chris.__proto__.__proto__ == WorkerBee.prototype;
-chris.__proto__.__proto__.__proto__ == Employee.prototype;
-chris.__proto__.__proto__.__proto__.__proto__ == Object.prototype;
-chris.__proto__.__proto__.__proto__.__proto__.__proto__ == null;
-
- -

Given this, you could write an instanceOf function as follows:

- -
function instanceOf(object, constructor) {
-   object = object.__proto__;
-   while (object != null) {
-      if (object == constructor.prototype)
-         return true;
-      if (typeof object == 'xml') {
-        return constructor.prototype == XML.prototype;
-      }
-      object = object.__proto__;
-   }
-   return false;
-}
-
- -
Note: The implementation above checks the type of the object against "xml" in order to work around a quirk of how XML objects are represented in recent versions of JavaScript. See {{ bug(634150) }} if you want the nitty-gritty details.
- -

Using the instanceOf function defined above, these expressions are true:

- -
instanceOf (chris, Engineer)
-instanceOf (chris, WorkerBee)
-instanceOf (chris, Employee)
-instanceOf (chris, Object)
-
- -

But the following expression is false:

- -
instanceOf (chris, SalesPerson)
-
- -

Informação global nos construtores

- -

When you create constructors, you need to be careful if you set global information in the constructor. For example, assume that you want a unique ID to be automatically assigned to each new employee. You could use the following definition for Employee:

- -
var idCounter = 1;
-
-function Employee (name, dept) {
-   this.name = name || "";
-   this.dept = dept || "general";
-   this.id = idCounter++;
-}
-
- -

With this definition, when you create a new Employee, the constructor assigns it the next ID in sequence and then increments the global ID counter. So, if your next statement is the following, victoria.id is 1 and harry.id is 2:

- -
var victoria = new Employee("Pigbert, Victoria", "pubs")
-var harry = new Employee("Tschopik, Harry", "sales")
-
- -

At first glance that seems fine. However, idCounter gets incremented every time an Employee object is created, for whatever purpose. If you create the entire Employee hierarchy shown in this chapter, the Employee constructor is called every time you set up a prototype. Suppose you have the following code:

- -
var idCounter = 1;
-
-function Employee (name, dept) {
-   this.name = name || "";
-   this.dept = dept || "general";
-   this.id = idCounter++;
-}
-
-function Manager (name, dept, reports) {...}
-Manager.prototype = new Employee;
-
-function WorkerBee (name, dept, projs) {...}
-WorkerBee.prototype = new Employee;
-
-function Engineer (name, projs, mach) {...}
-Engineer.prototype = new WorkerBee;
-
-function SalesPerson (name, projs, quota) {...}
-SalesPerson.prototype = new WorkerBee;
-
-var mac = new Engineer("Wood, Mac");
-
- -

Further assume that the definitions omitted here have the base property and call the constructor above them in the prototype chain. In this case, by the time the mac object is created, mac.id is 5.

- -

Depending on the application, it may or may not matter that the counter has been incremented these extra times. If you care about the exact value of this counter, one possible solution involves instead using the following constructor:

- -
function Employee (name, dept) {
-   this.name = name || "";
-   this.dept = dept || "general";
-   if (name)
-      this.id = idCounter++;
-}
-
- -

When you create an instance of Employee to use as a prototype, you do not supply arguments to the constructor. Using this definition of the constructor, when you do not supply arguments, the constructor does not assign a value to the id and does not update the counter. Therefore, for an Employee to get an assigned id, you must specify a name for the employee. In this example, mac.id would be 1.

- -

No multiple inheritance

- -

Some object-oriented languages allow multiple inheritance. That is, an object can inherit the properties and values from unrelated parent objects. JavaScript does not support multiple inheritance.

- -

Inheritance of property values occurs at run time by JavaScript searching the prototype chain of an object to find a value. Because an object has a single associated prototype, JavaScript cannot dynamically inherit from more than one prototype chain.

- -

In JavaScript, you can have a constructor function call more than one other constructor function within it. This gives the illusion of multiple inheritance. For example, consider the following statements:

- -
function Hobbyist (hobby) {
-   this.hobby = hobby || "scuba";
-}
-
-function Engineer (name, projs, mach, hobby) {
-   this.base1 = WorkerBee;
-   this.base1(name, "engineering", projs);
-   this.base2 = Hobbyist;
-   this.base2(hobby);
-   this.machine = mach || "";
-}
-Engineer.prototype = new WorkerBee;
-
-var dennis = new Engineer("Doe, Dennis", ["collabra"], "hugo")
-
- -

Further assume that the definition of WorkerBee is as used earlier in this chapter. In this case, the dennis object has these properties:

- -
dennis.name == "Doe, Dennis"
-dennis.dept == "engineering"
-dennis.projects == ["collabra"]
-dennis.machine == "hugo"
-dennis.hobby == "scuba"
-
- -

So dennis does get the hobby property from the Hobbyist constructor. However, assume you then add a property to the Hobbyist constructor's prototype:

- -
Hobbyist.prototype.equipment = ["mask", "fins", "regulator", "bcd"]
-
- -

The dennis object does not inherit this new property.

- -
{{PreviousNext("Web/JavaScript/Guide/Working_with_Objects", "Web/JavaScript/Guide/Iterators_and_Generators")}}
diff --git a/files/pt-pt/web/javascript/guide/grammar_and_types/index.html b/files/pt-pt/web/javascript/guide/grammar_and_types/index.html deleted file mode 100644 index 511fe9d281..0000000000 --- a/files/pt-pt/web/javascript/guide/grammar_and_types/index.html +++ /dev/null @@ -1,642 +0,0 @@ ---- -title: Gramática e tipos -slug: Web/JavaScript/Guide/Grammar_and_types -tags: - - Guia(2) - - JavaScript -translation_of: Web/JavaScript/Guide/Grammar_and_types -original_slug: Web/JavaScript/Guia/Gramática_e_tipos ---- -
{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Introduction", "Web/JavaScript/Guide/Control_flow_and_error_handling")}}
- -

Este capítulo discute a gramática básica do JavaScript, declarações de variáveis, tipos de dados e literais.

- -

Básicos

- -

JavaScript borrows most of its syntax from Java, but is also influenced by Awk, Perl and Python.

- -

JavaScript is case-sensitive and uses the Unicode character set.

- -

In JavaScript, instructions are called {{Glossary("Statement", "statements")}} and are separated by a semicolon (;). Spaces, tabs and newline characters are called whitespace. The source text of JavaScript scripts gets scanned from left to right and is converted into a sequence of input elements which are tokens, control characters, line terminators, comments or whitespace. ECMAScript also defines certain keywords and literals and has rules for automatic insertion of semicolons (ASI) to end statements. However, it is recommended to always add semicolons to end your statements; it will avoid side effects. For more information, see the detailed reference about JavaScript's lexical grammar.

- -

Comentários

- -

The syntax of comments is the same as in C++ and in many other languages:

- -
// a one line comment
-
-/* this is a longer,
-   multi-line comment
- */
-
-/* You can't, however, /* nest comments */ SyntaxError */
- -

Declarações

- -

There are three kinds of declarations in JavaScript.

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

Variáveis

- -

You use variables as symbolic names for values in your application. The names of variables, called {{Glossary("Identifier", "identifiers")}}, conform to certain rules.

- -

A JavaScript identifier must start with a letter, underscore (_), or dollar sign ($); subsequent characters can also be digits (0-9). Because JavaScript is case sensitive, letters include the characters "A" through "Z" (uppercase) and the characters "a" through "z" (lowercase).

- -

You can use ISO 8859-1 or Unicode letters such as å and ü in identifiers. You can also use the Unicode escape sequences as characters in identifiers.

- -

Some examples of legal names are Number_hits, temp99, and _name.

- -

Declararação de variáveis

- -

You can declare a variable in three ways:

- - - -

Avaliação de variáveis

- -

A variable declared using the var statement with no initial value specified has the value {{jsxref("undefined")}}.

- -

An attempt to access an undeclared variable or an attempt to access an identifier declared with let statement before initialization will result in a {{jsxref("ReferenceError")}} exception being thrown:

- -
var a;
-console.log("The value of a is " + a); // logs "The value of a is undefined"
-console.log("The value of b is " + b); // throws ReferenceError exception
-
-console.log("The value of x is " + x); // throws ReferenceError exception
-let x; 
- -

You can use undefined to determine whether a variable has a value. In the following code, the variable input is not assigned a value, and the if statement evaluates to true.

- -
var input;
-if(input === undefined){
-  doThis();
-} else {
-  doThat();
-}
-
- -

The undefined value behaves as false when used in a boolean context. For example, the following code executes the function myFunction because the myArray element is undefined:

- -
var myArray = [];
-if (!myArray[0]) myFunction();
-
- -

The undefined value converts to NaN when used in numeric context.

- -
var a;
-a + 2;  // Evaluates to NaN
- -

When you evaluate a {{jsxref("null")}} variable, the null value behaves as 0 in numeric contexts and as false in boolean contexts. For example:

- -
var n = null;
-console.log(n * 32); // Will log 0 to the console
-
- -

Variable scope

- -

When you declare a variable outside of any function, it is called a global variable, because it is available to any other code in the current document. When you declare a variable within a function, it is called a local variable, because it is available only within that function.

- -

JavaScript before ECMAScript 2015 does not have block statement scope; rather, a variable declared within a block is local to the function (or global scope) that the block resides within. For example the following code will log 5, because the scope of x is the function (or global context) within which x is declared, not the block, which in this case is an if statement.

- -
if (true) {
-  var x = 5;
-}
-console.log(x);  // 5
-
- -

This behavior changes, when using the let declaration introduced in ECMAScript 2015.

- -
if (true) {
-  let y = 5;
-}
-console.log(y);  // ReferenceError: y is not defined
-
- -

Variable hoisting

- -

Another unusual thing about variables in JavaScript is that you can refer to a variable declared later, without getting an exception. This concept is known as hoisting; variables in JavaScript are in a sense "hoisted" or lifted to the top of the function or statement. However, variables that are hoisted will return a value of undefined. So even if you declare and initialize after you use or refer to this variable, it will still return undefined.

- -
/**
- * Example 1
- */
-console.log(x === undefined); // true
-var x = 3;
-
-/**
- * Example 2
- */
-// will return a value of undefined
-var myvar = "my value";
-
-(function() {
-  console.log(myvar); // undefined
-  var myvar = "local value";
-})();
-
- -

The above examples will be interpreted the same as:

- -
/**
- * Example 1
- */
-var x;
-console.log(x === undefined); // true
-x = 3;
-
-/**
- * Example 2
- */
-var myvar = "my value";
-
-(function() {
-  var myvar;
-  console.log(myvar); // undefined
-  myvar = "local value";
-})();
-
- -

Because of hoisting, all var statements in a function should be placed as near to the top of the function as possible. This best practice increases the clarity of the code.

- -

In ECMAScript 2015, let (const) will not hoist the variable to the top of the block. However, referencing the variable in the block before the variable declaration results in a ReferenceError. The variable is in a "temporal dead zone" from the start of the block until the declaration is processed.

- -
console.log(x); // ReferenceError
-let x = 3;
- -

Variáveis gGlobais

- -

Global variables are in fact properties of the global object. In web pages the global object is {{domxref("window")}}, so you can set and access global variables using the window.variable syntax.

- -

Consequently, you can access global variables declared in one window or frame from another window or frame by specifying the window or frame name. For example, if a variable called phoneNumber is declared in a document, you can refer to this variable from an iframe as parent.phoneNumber.

- -

Constantes

- -

You can create a read-only, named constant with the {{jsxref("Statements/const", "const")}} keyword. The syntax of a constant identifier is the same as for a variable identifier: it must start with a letter, underscore or dollar sign and can contain alphabetic, numeric, or underscore characters.

- -
const PI = 3.14;
-
- -

A constant cannot change value through assignment or be re-declared while the script is running. It has to be initialized to a value.

- -

The scope rules for constants are the same as those for let block scope variables. If the const keyword is omitted, the identifier is assumed to represent a variable.

- -

You cannot declare a constant with the same name as a function or variable in the same scope. For example:

- -
// THIS WILL CAUSE AN ERROR
-function f() {};
-const f = 5;
-
-// THIS WILL CAUSE AN ERROR ALSO
-function f() {
-  const g = 5;
-  var g;
-
-  //statements
-}
-
- -

However, object attributes are not protected, so the following statement is executed without problems.

- -
const MY_OBJECT = {"key": "value"};
-MY_OBJECT.key = "otherValue";
- -

Estruturas e tipode dados

- -

tipos de dados

- -

The latest ECMAScript standard defines seven data types:

- - - -

Although these data types are a relatively small amount, they enable you to perform useful functions with your applications. {{jsxref("Object", "Objects")}} and {{jsxref("Function", "functions")}} are the other fundamental elements in the language. You can think of objects as named containers for values, and functions as procedures that your application can perform.

- -

Conversão de tipo de dados

- -

JavaScript is a dynamically typed language. That means you don't have to specify the data type of a variable when you declare it, and data types are converted automatically as needed during script execution. So, for example, you could define a variable as follows:

- -
var answer = 42;
-
- -

And later, you could assign the same variable a string value, for example:

- -
answer = "Thanks for all the fish...";
-
- -

Because JavaScript is dynamically typed, this assignment does not cause an error message.

- -

In expressions involving numeric and string values with the + operator, JavaScript converts numeric values to strings. For example, consider the following statements:

- -
x = "The answer is " + 42 // "The answer is 42"
-y = 42 + " is the answer" // "42 is the answer"
-
- -

In statements involving other operators, JavaScript does not convert numeric values to strings. For example:

- -
"37" - 7 // 30
-"37" + 7 // "377"
-
- -

Conversão de strings para números

- -

In the case that a value representing a number is in memory as a string, there are methods for conversion.

- - - -

parseInt will only return whole numbers, so its use is diminished for decimals. Additionally, a best practice for parseInt is to always include the radix parameter. The radix parameter is used to specify which numerical system is to be used.

- -

An alternative method of retrieving a number from a string is with the + (unary plus) operator:

- -
"1.1" + "1.1" = "1.11.1"
-(+"1.1") + (+"1.1") = 2.2
-// Note: the parentheses are added for clarity, not required.
- -

Literais

- -

You use literals to represent values in JavaScript. These are fixed values, not variables, that you literally provide in your script. This section describes the following types of literals:

- - - -

Literais de tabela

- -

An array literal is a list of zero or more expressions, each of which represents an array element, enclosed in square brackets ([]). When you create an array using an array literal, it is initialized with the specified values as its elements, and its length is set to the number of arguments specified.

- -

The following example creates the coffees array with three elements and a length of three:

- -
var coffees = ["French Roast", "Colombian", "Kona"];
-
- -
-

Note : An array literal is a type of object initializer. See Using Object Initializers.

-
- -

If an array is created using a literal in a top-level script, JavaScript interprets the array each time it evaluates the expression containing the array literal. In addition, a literal used in a function is created each time the function is called.

- -

Array literals are also Array objects. See {{jsxref("Array")}} and Indexed collections for details on Array objects.

- -

Extra commas in array literals

- -

You do not have to specify all elements in an array literal. If you put two commas in a row, the array is created with undefined for the unspecified elements. The following example creates the fish array:

- -
var fish = ["Lion", , "Angel"];
-
- -

This array has two elements with values and one empty element (fish[0] is "Lion", fish[1] is undefined, and fish[2] is "Angel").

- -

If you include a trailing comma at the end of the list of elements, the comma is ignored. In the following example, the length of the array is three. There is no myList[3]. All other commas in the list indicate a new element.

- -
-

Nota : Trailing commas can create errors in older browser versions and it is a best practice to remove them.

-
- -
var myList = ['home', , 'school', ];
-
- -

In the following example, the length of the array is four, and myList[0] and myList[2] are missing.

- -
var myList = [ , 'home', , 'school'];
-
- -

In the following example, the length of the array is four, and myList[1] and myList[3] are missing. Only the last comma is ignored.

- -
var myList = ['home', , 'school', , ];
-
- -

Understanding the behavior of extra commas is important to understanding JavaScript as a language, however when writing your own code: explicitly declaring the missing elements as undefined will increase your code's clarity and maintainability.

- -

Lietrais boolianas

- -

The Boolean type has two literal values: true and false.

- -

Do not confuse the primitive Boolean values true and false with the true and false values of the Boolean object. The Boolean object is a wrapper around the primitive Boolean data type. See {{jsxref("Boolean")}} for more information.

- -

Íntegros

- -

Integers can be expressed in decimal (base 10), hexadecimal (base 16), octal (base 8) and binary (base 2).

- - - -

Some examples of integer literals are:

- -
0, 117 and -345 (decimal, base 10)
-015, 0001 and -0o77 (octal, base 8)
-0x1123, 0x00111 and -0xF1A7 (hexadecimal, "hex" or base 16)
-0b11, 0b0011 and -0b11 (binary, base 2)
-
- -

For more information, see Numeric literals in the Lexical grammar reference.

- -

Literais de ponto flutuante

- -

A floating-point literal can have the following parts:

- - - -

The exponent part is an "e" or "E" followed by an integer, which can be signed (preceded by "+" or "-"). A floating-point literal must have at least one digit and either a decimal point or "e" (or "E").

- -

More succinctly, the syntax is:

- -
[(+|-)][digits][.digits][(E|e)[(+|-)]digits]
-
- -

For example:

- -
3.1415926
--.123456789
--3.1E+12
-.1e-23
-
- -

Literais de objeto

- -

An object literal is a list of zero or more pairs of property names and associated values of an object, enclosed in curly braces ({}). You should not use an object literal at the beginning of a statement. This will lead to an error or not behave as you expect, because the { will be interpreted as the beginning of a block.

- -

The following is an example of an object literal. The first element of the car object defines a property, myCar, and assigns to it a new string, "Saturn"; the second element, the getCar property, is immediately assigned the result of invoking the function (carTypes("Honda")); the third element, the special property, uses an existing variable (sales).

- -
var sales = "Toyota";
-
-function carTypes(name) {
-  if (name === "Honda") {
-    return name;
-  } else {
-    return "Sorry, we don't sell " + name + ".";
-  }
-}
-
-var car = { myCar: "Saturn", getCar: carTypes("Honda"), special: sales };
-
-console.log(car.myCar);   // Saturn
-console.log(car.getCar);  // Honda
-console.log(car.special); // Toyota
-
- -

Additionally, you can use a numeric or string literal for the name of a property or nest an object inside another. The following example uses these options.

- -
var car = { manyCars: {a: "Saab", "b": "Jeep"}, 7: "Mazda" };
-
-console.log(car.manyCars.b); // Jeep
-console.log(car[7]); // Mazda
-
- -

Object property names can be any string, including the empty string. If the property name would not be a valid JavaScript {{Glossary("Identifier","identifier")}} or number, it must be enclosed in quotes. Property names that are not valid identifiers also cannot be accessed as a dot (.) property, but can be accessed and set with the array-like notation("[]").

- -
var unusualPropertyNames = {
-  "": "An empty string",
-  "!": "Bang!"
-}
-console.log(unusualPropertyNames."");   // SyntaxError: Unexpected string
-console.log(unusualPropertyNames[""]);  // An empty string
-console.log(unusualPropertyNames.!);    // SyntaxError: Unexpected token !
-console.log(unusualPropertyNames["!"]); // Bang!
- -

In ES2015, object literals are extended to support setting the prototype at construction, shorthand for foo: foo assignments, defining methods, making super calls, and computing property names with expressions. Together, these also bring object literals and class declarations closer together, and let object-based design benefit from some of the same conveniences.

- -
var obj = {
-    // __proto__
-    __proto__: theProtoObj,
-    // Shorthand for ‘handler: handler’
-    handler,
-    // Methods
-    toString() {
-     // Super calls
-     return "d " + super.toString();
-    },
-    // Computed (dynamic) property names
-    [ 'prop_' + (() => 42)() ]: 42
-};
- -

Por favor, note:

- -
var foo = {a: "alpha", 2: "two"};
-console.log(foo.a);    // alpha
-console.log(foo[2]);   // two
-//console.log(foo.2);  // Error: missing ) after argument list
-//console.log(foo[a]); // Error: a is not defined
-console.log(foo["a"]); // alpha
-console.log(foo["2"]); // two
-
- -

RegExp literals

- -

A regex literal is a pattern enclosed between slashes. The following is an example of an regex literal.

- -
var re = /ab+c/;
- -

Lietrais de string

- -

A string literal is zero or more characters enclosed in double (") or single (') quotation marks. A string must be delimited by quotation marks of the same type; that is, either both single quotation marks or both double quotation marks. The following are examples of string literals:

- -
"foo"
-'bar'
-"1234"
-"one line \n another line"
-"John's cat"
-
- -

You can call any of the methods of the String object on a string literal value—JavaScript automatically converts the string literal to a temporary String object, calls the method, then discards the temporary String object. You can also use the String.length property with a string literal:

- -
console.log("John's cat".length)
-// Will print the number of symbols in the string including whitespace.
-// In this case, 10.
-
- -

In ES2015, template literals are also available. Template strings provide syntactic sugar for constructing strings. This is similar to string interpolation features in Perl, Python and more. Optionally, a tag can be added to allow the string construction to be customized, avoiding injection attacks or constructing higher level data structures from string contents.

- -
// Basic literal string creation
-`In JavaScript '\n' is a line-feed.`
-
-// Multiline strings
-`In JavaScript this is
- not legal.`
-
-// String interpolation
-var name = "Bob", time = "today";
-`Hello ${name}, how are you ${time}?`
-
-// Construct an HTTP request prefix is used to interpret the replacements and construction
-POST`http://foo.org/bar?a=${a}&b=${b}
-     Content-Type: application/json
-     X-Credentials: ${credentials}
-     { "foo": ${foo},
-       "bar": ${bar}}`(myOnReadyStateChangeHandler);
- -

You should use string literals unless you specifically need to use a String object. See {{jsxref("String")}} for details on String objects.

- -

Using special characters in strings

- -

In addition to ordinary characters, you can also include special characters in strings, as shown in the following example.

- -
"one line \n another line"
-
- -

The following table lists the special characters that you can use in JavaScript strings.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Table: JavaScript special characters
CáraterSignificado
\0Null Byte
\bBackspace
\fForm feed
\nNew line
\rCarriage return
\tTab
\vVertical tab
\'Apostrophe or single quote
\"Double quote
\\Backslash character
\XXXThe character with the Latin-1 encoding specified by up to three octal digits XXX between 0 and 377. For example, \251 is the octal sequence for the copyright symbol.
\xXXThe character with the Latin-1 encoding specified by the two hexadecimal digits XX between 00 and FF. For example, \xA9 is the hexadecimal sequence for the copyright symbol.
\uXXXXThe Unicode character specified by the four hexadecimal digits XXXX. For example, \u00A9 is the Unicode sequence for the copyright symbol. See Unicode escape sequences.
\u{XXXXX}Unicode code point escapes. For example, \u{2F804} is the same as the simple Unicode escapes \uD87E\uDC04.
- -

Escaping characters

- -

For characters not listed in the table, a preceding backslash is ignored, but this usage is deprecated and should be avoided.

- -

You can insert a quotation mark inside a string by preceding it with a backslash. This is known as escaping the quotation mark. For example:

- -
var quote = "He read \"The Cremation of Sam McGee\" by R.W. Service.";
-console.log(quote);
-
- -

The result of this would be:

- -
He read "The Cremation of Sam McGee" by R.W. Service.
-
- -

To include a literal backslash inside a string, you must escape the backslash character. For example, to assign the file path c:\temp to a string, use the following:

- -
var home = "c:\\temp";
-
- -

You can also escape line breaks by preceding them with backslash. The backslash and line break are both removed from the value of the string.

- -
var str = "this string \
-is broken \
-across multiple\
-lines."
-console.log(str);   // this string is broken across multiplelines.
-
- -

Although JavaScript does not have "heredoc" syntax, you can get close by adding a line break escape and an escaped line break at the end of each line:

- -
var poem =
-"Roses are red,\n\
-Violets are blue.\n\
-Sugar is sweet,\n\
-and so is foo."
-
- -

Mais informação

- -

This chapter focuses on basic syntax for declarations and types. To learn more about JavaScript's language constructs, see also the following chapters in this guide:

- - - -

In the next chapter, we will have a look at control flow constructs and error handling.

- -

{{PreviousNext("Web/JavaScript/Guide/Introduction", "Web/JavaScript/Guide/Control_flow_and_error_handling")}}

diff --git a/files/pt-pt/web/javascript/guide/index.html b/files/pt-pt/web/javascript/guide/index.html deleted file mode 100644 index 50779449a1..0000000000 --- a/files/pt-pt/web/javascript/guide/index.html +++ /dev/null @@ -1,124 +0,0 @@ ---- -title: Guia de JavaScript -slug: Web/JavaScript/Guide -tags: - - Guía - - JavaScript - - l10n:prioridade -translation_of: Web/JavaScript/Guide -original_slug: Web/JavaScript/Guia ---- -
{{jsSidebar("JavaScript Guide")}}
- -

The JavaScript Guide shows you how to use JavaScript and gives an overview of the language. If you want to get started with JavaScript or programming in general, consult the articles in the learning area. If you need exhaustive information about a language feature, have a look at the JavaScript reference.

- -

Capítulos

- -

This Guide is divided into several chapters:

- - - - - - - - - -

{{Next("Web/JavaScript/Guide/Introduction")}}

diff --git a/files/pt-pt/web/javascript/guide/introduction/index.html b/files/pt-pt/web/javascript/guide/introduction/index.html deleted file mode 100644 index eddebd2e98..0000000000 --- a/files/pt-pt/web/javascript/guide/introduction/index.html +++ /dev/null @@ -1,138 +0,0 @@ ---- -title: Introdução -slug: Web/JavaScript/Guide/Introduction -tags: - - Guía - - JavaScript -translation_of: Web/JavaScript/Guide/Introduction -original_slug: Web/JavaScript/Guia/Introdução ---- -
{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide", "Web/JavaScript/Guide/Grammar_and_types")}}
- -

Este capítulo apresenta a linguagem JavaScript e discuste alguns dos seus conceitos fundamentais.

- -

O que você já deveria saber

- -

Este guia assume que você possuí os seguintes conhecimentos:

- - - -

Onde encontrar informação sobre JavaScript?

- -

A documentação de JavaScript no MDN incluí o seguinte:

- - - -

Se for iniciante em JavaScript, comece lendo alguns dos artigos na área de aprendizagem e o  Guia de JavaScript. Assim que compreender os fundamentos da linguagem, pode consultar a Referência de JavaScript para obter mais detalhes sobre objetos individuais e declarações.

- -

O que é JavaScript?

- -

JavaScript é uma linguagem de script orientada a objetos e que funciona entre plataformas. É uma linguagem pequena e simples. Ela pode ser rodada num ambiente anfitrião (por exemplo, o browser),  o código JavaScript pode estar ligado a objetos do ambiente e  fornece controle programático sobre os mesmos.

- -

O JavaScript contém uma biblioteca padrão de objetos, tais como ArrayDateMath, e um conjunto fundamental de elementos da linguagem tais como operadores, estruturas de controle, e statements. Os elementos básicos do JavaScript podem ser extendidos com objetos adicionais para uma variedade de propósitos, por exemplo:

- - - -

JavaScript e Java

- -

JavaScript e Java são linguagens similares em alguns aspetos mas fundamentalmente diferentes noutros. A linguagem JavaScript assemelha-se ao Java mas não tem o static typing nem a validação strong type. O JavaScsript segue a sintaxe de expressões do Java, convenções de nomenclatura e os construtores básicos de controlo de fluxo. Esta última foi a razão pelo qual a linguagem foi renomeada de LiveScript para JavaScript.

- -

In contrast to Java's compile-time system of classes built by declarations, JavaScript supports a runtime system based on a small number of data types representing numeric, Boolean, and string values. JavaScript has a prototype-based object model instead of the more common class-based object model. The prototype-based model provides dynamic inheritance; that is, what is inherited can vary for individual objects. JavaScript also supports functions without any special declarative requirements. Functions can be properties of objects, executing as loosely typed methods.

- -

JavaScript is a very free-form language compared to Java. You do not have to declare all variables, classes, and methods. You do not have to be concerned with whether methods are public, private, or protected, and you do not have to implement interfaces. Variables, parameters, and function return types are not explicitly typed.

- -

Java is a class-based programming language designed for fast execution and type safety. Type safety means, for instance, that you can't cast a Java integer into an object reference or access private memory by corrupting Java bytecodes. Java's class-based model means that programs consist exclusively of classes and their methods. Java's class inheritance and strong typing generally require tightly coupled object hierarchies. These requirements make Java programming more complex than JavaScript programming.

- -

In contrast, JavaScript descends in spirit from a line of smaller, dynamically typed languages such as HyperTalk and dBASE. These scripting languages offer programming tools to a much wider audience because of their easier syntax, specialized built-in functionality, and minimal requirements for object creation.

- - - - - - - - - - - - - - - - - - - - - - - -
JavaScript comparado com Java
JavaScriptJava
Object-oriented. No distinction between types of objects. Inheritance is through the prototype mechanism, and properties and methods can be added to any object dynamically.Class-based. Objects are divided into classes and instances with all inheritance through the class hierarchy. Classes and instances cannot have properties or methods added dynamically.
Variable data types are not declared (dynamic typing).Variable data types must be declared (static typing).
Cannot automatically write to hard disk.Can automatically write to hard disk.
- -

For more information on the differences between JavaScript and Java, see the chapter Details of the object model.

- -

JavaScript e a especificação ECMAScript

- -

JavaScript is standardized at Ecma International — the European association for standardizing information and communication systems (ECMA was formerly an acronym for the European Computer Manufacturers Association) to deliver a standardized, international programming language based on JavaScript. This standardized version of JavaScript, called ECMAScript, behaves the same way in all applications that support the standard. Companies can use the open standard language to develop their implementation of JavaScript. The ECMAScript standard is documented in the ECMA-262 specification. See New in JavaScript to learn more about different versions of JavaScript and ECMAScript specification editions.

- -

The ECMA-262 standard is also approved by the ISO (International Organization for Standardization) as ISO-16262. You can also find the specification on the Ecma International website. The ECMAScript specification does not describe the Document Object Model (DOM), which is standardized by the World Wide Web Consortium (W3C) and/or WHATWG (Web Hypertext Application Technology Working Group). The DOM defines the way in which HTML document objects are exposed to your script. To get a better idea about the different technologies that are used when programming with JavaScript, consult the article JavaScript technologies overview.

- -

Documentação JavaScript versus especificação  ECMAScript

- -

The ECMAScript specification is a set of requirements for implementing ECMAScript; it is useful if you want to implement standards-compliant language features in your ECMAScript implementation or engine (such as SpiderMonkey in Firefox, or v8 in Chrome).

- -

The ECMAScript document is not intended to help script programmers; use the JavaScript documentation for information on writing scripts.

- -

The ECMAScript specification uses terminology and syntax that may be unfamiliar to a JavaScript programmer. Although the description of the language may differ in ECMAScript, the language itself remains the same. JavaScript supports all functionality outlined in the ECMAScript specification.

- -

The JavaScript documentation describes aspects of the language that are appropriate for a JavaScript programmer.

- -

Começar com JavaScript

- -

Getting started with JavaScript is easy: all you need is a modern Web browser. This guide includes some JavaScript features which are only currently available in the latest versions of Firefox, so using the most recent version of Firefox is recommended.

- -

There are two tools built into Firefox that are useful for experimenting with JavaScript: the Web Console and Scratchpad.

- -

A Consola da Web

- -

A Consola da Web shows you information about the currently loaded Web page, and also includes a command line that you can use to execute JavaScript expressions in the current page.

- -

To open the Web Console (Ctrl+Shift+K), select "Web Console" from the "Developer" menu, which is under the "Tools" menu in Firefox. It appears at the bottom of the browser window. Along the bottom of the console is a command line that you can use to enter JavaScript, and the output appears in the pane above:

- -

- -

Scratchpad

- -

The Web Console is great for executing single lines of JavaScript, but although you can execute multiple lines, it's not very convenient for that, and you can't save your code samples using the Web Console. So for more complex examples Scratchpad is a better tool.

- -

To open Scratchpad (Shift+F4), select "Scratchpad" from the "Developer" menu, which is under the menu in Firefox. It opens in a separate window and is an editor that you can use to write and execute JavaScript in the browser. You can also save scripts to disk and load them from disk.

- -

- -

Olá mundo

- -

To get started with writing JavaScript, open the Scratchpad and write your first "Hello world" JavaScript code:

- -
function greetMe(yourName) {
-  alert("Hello " + yourName);
-}
-
-greetMe("World");
-
- -

Select the code in the pad and hit Ctrl+R to watch it unfold in your browser!

- -

In the following pages, this guide will introduce you to the JavaScript syntax and language features, so that you will be able to write more complex applications.

- -

{{PreviousNext("Web/JavaScript/Guide", "Web/JavaScript/Guide/Grammar_and_types")}}

diff --git a/files/pt-pt/web/javascript/index.html b/files/pt-pt/web/javascript/index.html deleted file mode 100644 index 96b6b4b28b..0000000000 --- a/files/pt-pt/web/javascript/index.html +++ /dev/null @@ -1,140 +0,0 @@ ---- -title: JavaScript -slug: Web/JavaScript -tags: - - Aprender - - JavaScript - - Landing - - Página Landing - - 'l10n:priority' -translation_of: Web/JavaScript ---- -
{{JsSidebar}}
- -
-

JavaScript (JS) é uma linguagem de programação compilada simples, interpretada ou "just-in-time" com {{Glossary("First-class Function", "funções de primeira classe")}}. Embora seja mais conhecida coma a linguagem de scripting para as páginas da Web, também é utilizada em muitos ambientes além de navegadores (inglês), tais como Node.js, Apache CouchDB e Adobe Acrobat. JavaScript é uma linguagem dinâmica, {{Glossary("Prototype-based programming", "baseada em protótipos")}} e que suporta os paradigmas de programação orientada a objetos, imperativa e declarativa (incluindo programação funcional). Leia mais sobre o JavaScript.

- -

Esta secção do site é dedicada à própria linguagem JavaScript, e não a partes específicas das páginas da Internet ou outros ambientes. Para informação sobre {{Glossary("API","APIs")}} específicas para as páginas da Web, por favor, consulte APIs da Web e DOM.

- -

O padrão para JavaScript é ECMAScript. Em 2012, todos os navegadores modernos são totalmente compatíveis com a versão ECMAScript 5.1. Navegadores mais antigos suportam pelo menos ECMAScript 3. No dia 17 de junho de 2015, ECMA International publicou a sexta versão principal de ECMAScript, cujo nome oficial é ECMAScript 2015, e inicialmente era chamada ECMAScript 6 ou ES6. Desde então, as normas de ECMAScript são lançadas anualmente. Esta documentação refere-se à última proposta, que atualmente é ECMAScript 2018.

- -

Não faça confusão entre JavaScript e a linguagem de programação Java. Tanto "Java" como "JavaScript" são marcas ou marcas registadas da Oracle nos E.U.A. e outros países. Contudo, estas linguagens de programação têm muitas diferenças na sua sintaxe, semânticas e utilização.

- -
-
-

Tutoriais

- -

Aprender a programar em JavaScript com guias e tutorials.

- -

Para principiantes absolutos

- -

Dirija-se ao nosso tópico sobre JavaScript se quer aprender esta linguagem mas não tem experiência alguma em programação. Seguem-se os módulos disponíveis:

- -
-
JavaScript - primeiros passos
-
Responde a questões fundamentais como "o que é JavaScript?", "que aspeto tem a linguagem?", e "o que pode fazer?", além de discutir funcionalidades chave JavaScript como variáveis, strings, números e arrays.
-
JavaScript - elementos constituintes
-
Continua a abordagem às principais funcionalidades de JavaScript, tendo como foco os blocos de código utilizados mais habitualmente, tais como instruções condicionais, ciclos, funções e eventos.
-
Introducing JavaScript objects
-
The object-oriented nature of JavaScript is important to understand if you want to go further with your knowledge of the language and write more efficient code, therefore we've provided this module to help you.
-
Asynchronous JavaScript
-
Discusses asynchronous JavaScript, why it is important, and how it can be used to effectively handle potential blocking operations such as fetching resources from a server.
-
Client-side web APIs
-
Explores what APIs are, and how to use some of the most common APIs you'll come across often in your development work.
-
- -

Guia de JavaScript

- -
-
Guia de JavaScript
-
Um guia muito detalhado de JavaScript, apropriado para pessoas com experiência em JavaScript ou noutra linguagem.
-
- -

Intermediário

- -
-
Reintrodução ao JavaScript
-
Uma visão geral para quem acha que conhece o JavaScript.
-
- -
-
Estrutura de Dados no JavaScript
-
Uma visão geral das estruturas de dados disponíveis no JavaScript.
-
Equality comparisons and sameness
-
JavaScript provides three different value-comparison operations: strict equality using ===, loose equality using ==, and the {{jsxref("Global_Objects/Object/is", "Object.is()")}} method.
-
Closures
-
-

A closure is the combination of a function and the lexical environment within which that function was declared.

-
-
- -

Avançado

- -
-
Inheritance and the prototype chain
-
Explanation of the widely misunderstood and under-estimated prototype-based inheritance.
-
Strict mode
-
Strict mode defines that you can not use any variable before initializing it. It is a restricted variant of ECMAScript 5, for faster performance and easier debugging.
-
JavaScript typed arrays
-
JavaScript typed arrays provide a mechanism for accessing raw binary data.
-
Memory Management
-
Memory life cycle and garbage collection in JavaScript.
-
Concurrency model and Event Loop
-
JavaScript has a concurrency model based on an "event loop".
-
-
- -
-

Referência

- -

Explore a documentação completa de refrência de JavaScript.

- -
-
Standard objects
-
Get to know standard built-in objects {{jsxref("Array")}}, {{jsxref("Boolean")}}, {{jsxref("Date")}}, {{jsxref("Error")}}, {{jsxref("Function")}}, {{jsxref("JSON")}}, {{jsxref("Math")}}, {{jsxref("Number")}}, {{jsxref("Object")}}, {{jsxref("RegExp")}}, {{jsxref("String")}}, {{jsxref("Map")}}, {{jsxref("Set")}}, {{jsxref("WeakMap")}}, {{jsxref("WeakSet")}}, and others.
-
Expressions and operators
-
Learn more about the behavior of JavaScript's operators {{jsxref("Operators/instanceof", "instanceof")}}, {{jsxref("Operators/typeof", "typeof")}}, {{jsxref("Operators/new", "new")}}, {{jsxref("Operators/this", "this")}}, the operator precedence, and more.
-
Statements and declarations
-
Learn how {{jsxref("Statements/do...while", "do-while")}}, {{jsxref("Statements/for...in", "for-in")}}, {{jsxref("Statements/for...of", "for-of")}}, {{jsxref("Statements/try...catch", "try-catch")}}, {{jsxref("Statements/let", "let")}}, {{jsxref("Statements/var", "var")}}, {{jsxref("Statements/const", "const")}}, {{jsxref("Statements/if...else", "if-else")}}, {{jsxref("Statements/switch", "switch")}}, and more JavaScript statements and keywords work.
-
Funções
-
Aprenda como trabalhar com funções do JavaScript para desenvolver suas aplicações.
-
- -

Ferramentas e recursos

- -

Ferramentas úteis para escrever e depurar o seu código JavaScript.

- -
-
Ferramentas de Desenvolvimento do Firefox
-
Scratchpad, Consola da Web, JavaScript Profiler, Debugger, e muito mais.
-
JavaScript Shells
-
A JavaScript shell allows you to quickly test snippets of JavaScript code.
-
Learn JavaScript
-
An excellent resource for aspiring web developers — Learn JavaScript in an interactive environment, with short lessons and interactive tests, guided by automated assessment. The first 40 lessons are free, and the complete course is available for a small one-time payment.
-
TogetherJS
-
Collaboration made easy. By adding TogetherJS to your site, your users can help each other out on a website in real time!
-
Stack Overflow
-
Dúvidas no Stack Overflow marcadas com "JavaScript".
-
JavaScript versions and release notes
-
Browse JavaScript's feature history and implementation status.
-
JSFiddle
-
Edit JavaScript, CSS, HTML and get live results. Use external resources and collaborate with your team online.
-
-
Plunker
-
Plunker is an online community for creating, collaborating on and sharing your web development ideas. Edit your JavaScript, CSS, HTML files and get live results and file structure.
-
JSBin
-
-

JS Bin is an open source collaborative web development debugging tool.

-
-
Codepen
-
-

Codepen is another collaborative web development tool used as a live result playground.

-
-
StackBlitz
-
-

StackBlitz is another online playground/debugging tool, which can host and deploy full stack applications using React, Angular, etc.

-
-
-
-
-
diff --git a/files/pt-pt/web/javascript/memory_management/index.html b/files/pt-pt/web/javascript/memory_management/index.html deleted file mode 100644 index 3a9d60c6b9..0000000000 --- a/files/pt-pt/web/javascript/memory_management/index.html +++ /dev/null @@ -1,188 +0,0 @@ ---- -title: Gestão de memória -slug: Web/JavaScript/Memory_Management -tags: - - Desempenho - - JavaScript - - memoria -translation_of: Web/JavaScript/Memory_Management -original_slug: Web/JavaScript/Gestao_Memoria ---- -
{{JsSidebar("Advanced")}}
- -

Introdução

- -

Linguagens de baixo nível, como o C, têm funções pimitivas de gestão de memória, como por exemplo, malloc() e free(). Por outro lado, os valores em JavaScript são alocados quando coisas (objetos, variáveis de texto, etc.) são criadas e "automaticamente" libertadas da memória quando deixam de ser utilizadas. O último processo é chamado de coleção do lixo. Este "automatismo" é uma fonte de mal entendidos e transmite aos programadores de JavaScript ( e aos de outras linguagens de alto nível ) a impressão de que podem decidir não se preocupar com a gestão da memória. Isto é uma erro.

- -

Ciclo da duração da memória

- -

Independentemente da linguagem de programação, o ciclo da duração da memória é praticamente sempre o mesmo:

- -
    -
  1. Alocação da memória necessária
  2. -
  3. Utilização da memória alocada ( leitura, escrita )
  4. -
  5. Libertar a memória alocada quando já não é necessária
  6. -
- -

A segunda etapa é explícita em todas as linguagens. A primeira e a última etapa são explícitas em linguagens de baixo nível mas são, na sua maioria, implícitas em linguagens de alto nível como o JavaScript.

- -

Alocação no JavaScript

- -

Inicialização do valor

- -

Com o intuito de não incomodar o programador com alocações, o JavaScript fá-lo juntamente com a declaração de valores.

- -
var n = 123; // alocação da memória para um número
-var s = 'azerty'; // alocação de memória para um texto
-
-var o = {
-  a: 1,
-  b: null
-}; // alocação de memória para um objeto e o seu conteúdo
-
-// (similar ao objeto) alocação de memória para a matriz e
-// os seus valores
-var a = [1, null, 'abra'];
-
-function f(a) {
-  return a + 2;
-} // alocação de uma função (que é um objeto que pode ser chamado)
-
-// Expressões de funções também alocam um objeto
-someElement.addEventListener('click', function() {
-  someElement.style.backgroundColor = 'blue';
-}, false);
-
- -

Alocação através de chamadas de funções

- -

Algumas chamadas de funções resultam na alocação de um objeto.

- -
var d = new Date(); // alocação de um objeto Date
-
-var e = document.createElement('div'); // alocação de um elemento DOM
- -

Alguns métodos alocam novos valores ou objetos:

- -
var s = 'azerty';
-var s2 = s.substr(0, 3); // s2 é uma nova variável de texto
-// Dado que as variáveis de texto são de valor imutável,
-// o JavaScript pode decidir não alocar memória,
-// mas apenas armazenar o intervalo [0, 3].
-
-var a = ['ouais ouais', 'nan nan'];
-var a2 = ['generation', 'nan nan'];
-var a3 = a.concat(a2);
-// nova matriz de 4 elementos resultando
-// da concatenação dos elementos de a e a2
-
- -

Utilização de valores

- -

Basicamente, a utilização de valores significa a leitura e a escrita na memória alocada. Isto pode ser feito através da leitura ou escrita do valor de uma variável ou uma propriedade de um objeto ou até a passagem de um argumento para uma função.

- -

Remoção quando a memória já não é necessária

- -

A maioria dos problemas de gestão de memória aparecem nesta fase. A tarefa mais difícil é descobrir quando "a memória alocada já não é necessária". Em geral, requer que o programador determine quando, no seu código, este pedaço de memória já não é necessário e a liberte.

- -

Linguagens de alto nível têm embutidas um pedaço de código chamado "coleção de lixo", cuja tarefa é rastrear a alocação e uso da memória, para detetar quando um pedaço de memória já não é necessário e neste caso, automaticamente libertá-la. Este processo é uma aproximação dado que o problema geral de se saber quando um pedaço da memória é necessário, é indecisível ( não pode ser solucionado por um algoritmo ).

- -

Coleção de lixo

- -

Como mencionado anteriormente, o problema geral de automaticamente descobrir quando alguma ocupação de memória "já não é necessária", é indecisível. Como consequência, as coleções de lixo implementam uma restrição à solução para o problema em geral. Esta seção explicará as noções necessárias para se compreender os principais algoritmos da coleção de lixo e as suas limitações.

- -

Referências

- -

A noção principal dos algoritmos de coleção de lixo baseiam-se na noção de referência. Dentro do contexto da gestão de memória, um objeto é dito referenciar outro objeto, se o primeiro tiver acesso ao segundo ( quer implicitamente quer explicitamente ). Por exemplo, um objeto JavaScript tem uma referência ao seu protótipo ( referência implícita )  e aos valores das suas propriedades ( referência explícita ).

- -

Neste contexto, a noção de "objeto" é expandida a algo mais abrangente que um objeto JavaScript e também contém âmbitos de funções ( ou âmbito léxico global ).

- -

Contagem de referências na coleção de lixo

- -

Este é o algoritmo mais simples da coleção de lixo. Este algoritmo reduz a definição de "um objeto já não é necessário" para "um objeto já não é referenciado por nenhum outro objeto". Um objeto é considerado coletável para a coleção de lixo se tiver nenhuma referenciação por parte de outro objeto.

- -

Exemplo

- -
var o = {
-  a: {
-    b: 2
-  }
-};
-// 2 objetos criados. Um é referenciado por outro como sendo suas propriedades
-// O outro é referenciado por virtude ao ser assignado para a variável 'o'
-// Obviamente, nenhum podem ser coletado pela coleção de lixo
-
-
-var o2 = o; // A variável 'o2' é a segunda coisa que
-            // tem uma referência ao objeto
-o = 1;      // agora, o objeto que era originalmente o 'o' tem uma referência única
-            // corporificada pela variável 'o2'
-
-var oa = o2.a; // referência à propriedade 'a' do objeto.
-               // Este objeto tem agora 2 referências: uma como propriedade,
-               // a outra como variável 'oa'
-
-o2 = 'yo'; // O objeto que era o original 'o' tem agora zero
-           // referências a si próprio. Pode ser coletado para a coleção de lixo
-           // No entanto, a propriedade 'a' ainda é referenciada pela
-           // variável 'oa', logo não pode ser libertado
-
-oa = null; // A propriedade 'a' do objeto original 'o'
-           // tem zero referências a si próprio. Pode ser coletado para a  coleção de lixo.
-
- -

Limitação: ciclos

- -

Existe uma limitação no que se refere aos ciclos. No exemplo seguinte, dois objetos são criados e referenciam-se mutuamente, criando um ciclo. Estes sairão do âmbito depois de uma chamada a uma função e como tal, são efetivamente inúteis e podem ser libertados. No entanto, o algoritmo de contagem de referências considera que os dois objetos têm pelo menos uma referenciação; nenhum pode ser coletado para a coleção de lixo .

- -
function f() {
-  var o = {};
-  var o2 = {};
-  o.a = o2; // o referencia o2
-  o2.a = o; // o2 referencia o
-
-  return 'azerty';
-}
-
-f();
-
- -

Exemplo de aplicação real

- -

O Internet Explorer 6 e 7 são conhecidos por terem um coletor de contagem de referenciações de coleções de lixo para os objetos DOM. Os ciclos são um erro comum que podem gerar percas de memória:

- -
var div;
-window.onload = function() {
-  div = document.getElementById('myDivElement');
-  div.circularReference = div;
-  div.lotsOfData = new Array(10000).join('*');
-};
-
- -

No exemplo acima, o elemento DOM "myDivElement" tem uma referência circular a si próprio na propriedade "circularReference". Se a propriedade não for explicitamente removida ou anulada, o coletor de contagem de referências da coleção de lixo, irá sempre ter uma referenciação intacta e irá manter o elemento DOM na memória mesmo quando for removido da árvore DOM. Se o elemento DOM contém bastante dados ( ilustrado no exemplo acima com a propriedade "lotsOfData" ), a memória consumida por estes dados nunca será libertada.

- -

Algoritmo de marcação e limpeza

- -

Este algoritmo reduz a definição de "um objeto já não é necessário" para "um objeto é inalcançável".

- -

Este algoritmo assume o conhecimento de um conjunto de objetos chamados "roots" ( em JavaScript, a root - raiz - é um objeto global ). Periodicamente, a coleção de lixo começará pela raíz e procurará todos os objetos que são referenciados a partir desta; depois todos os que são referenciados a partir dos seguintes, etc.. Começando pela raiz, o coletor de lixo irá localizar objetos inalcançáveis; coletando-os.

- -

Este algoritmo é melhor do que o anterior dado que "um objeto tem zero referenciações" leva a um objeto inalcançável. O contrário não é verdade como vimos nos ciclos.

- -

Desde 2012, todos os modernos navegadores de Internet contêm um coletor de marcação e limpeza. Todos os melhoramentos feitos na área da coleção de lixo no JavaScript ( generalização / incrementação / concorrência / coleção de lixo paralela ) nos últimos anos são implemetações de melhoramento deste algoritmo, mas não melhoramentos do algoritmo de coleção de lixo em si nem a sua redução à definição de que quando "um objeto já não é necessário".

- -

Os ciclos já não são um problema.

- -

No primeiro exemplo acima, depois do retorno da chamada à função, 2 objetos já não são referenciados por algo alcançável no objeto global. Consequentemente, irão ser localizados pelo coletor da coleção de lixo.

- -

Limitações: os objetos necessitam de ser explicitamente inalcançáveis

- -

Apesar disto estar marcado como uma limitação, é um caso que raramente ocorre na prática pelo que é por isto que ninguém se preocupa muito com a coleção de lixo.

- -

Ver também

- - diff --git a/files/pt-pt/web/javascript/reference/about/index.html b/files/pt-pt/web/javascript/reference/about/index.html deleted file mode 100644 index 2f9aaa49ac..0000000000 --- a/files/pt-pt/web/javascript/reference/about/index.html +++ /dev/null @@ -1,53 +0,0 @@ ---- -title: Sobre a referência de JavaScript -slug: Web/JavaScript/Reference/About -tags: - - JavaScript -translation_of: Web/JavaScript/Reference/About -original_slug: Web/JavaScript/Reference/Sobre ---- -
{{JsSidebar}}
- -

The JavaScript reference serves as a repository of facts about the JavaScript language. The entire language is described here in detail. As you write JavaScript code, you'll refer to these pages often (thus the title "JavaScript reference"). If you're learning JavaScript, or need help understanding some of its capabilities or features, check out the JavaScript guide.

- -

The JavaScript language is intended to be used within some larger environment, be it a browser, server-side scripts, or similar. For the most part, this reference attempts to be environment-agnostic and does not target a web browser environment.

- -

Onde encontrar informação sobre JavaScript

- -

JavaScript documentation of core language features (pure ECMAScript, for the most part) includes the following:

- - - -

If you are new to JavaScript, start with the guide. Once you have a firm grasp of the fundamentals, you can use the reference to get more details on individual objects and language constructs.

- -

Estrutura da referência

- -

In the JavaScript reference you can find the following chapters:

- -
-
Standard built-in objects
-
This chapter documents all the JavaScript standard built-in objects, along with their methods and properties.
-
Statements and declarations
-
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.
-
Expressions and operators
-
This chapter documents all the JavaScript language operators, expressions and keywords.
-
Functions
-
Chapter about JavaScript functions.
-
Classes
-
Chapter about JavaScript classes introduced in ECMAScript 6.
-
Errors
-
Chapter about specific errors, exceptions and warnings thrown by JavaScript.
-
New in JavaScript
-
Chapter about JavaScript version history.
-
- -

Mais páginas de referência

- - diff --git a/files/pt-pt/web/javascript/reference/classes/index.html b/files/pt-pt/web/javascript/reference/classes/index.html deleted file mode 100644 index 03ff413025..0000000000 --- a/files/pt-pt/web/javascript/reference/classes/index.html +++ /dev/null @@ -1,437 +0,0 @@ ---- -title: Classes -slug: Web/JavaScript/Reference/Classes -tags: - - Classes - - Construtores - - ECMAScript 2015 - - Herança - - Intermedio - - JavaScript -translation_of: Web/JavaScript/Reference/Classes ---- -
{{JsSidebar("Classes")}}
- -

Classes JavaScript , introduzidas no ECMAScript de 2015, são principalemente syntactical sugar sobre a herança baseada em prototipagem do JavaScript. A sintaxe de classe não introduz no JavaScript nenhum novo modelo de herança do paradigma das linguagens orientado a objetos .

- -

Definição de classes

- -

As classes são na realidade "funções especiais", e, tal como você pode definir o expressões de funções e declarações de funções, a sintaxe de classe tem dois componentes: expressões de classes e a declaração da classe.

- -

Declaração de classes

- -

Uma forma de definir uma classe é usar uma declaração de classe. Para declarar uma classe, utiliza-se a palavra reservada class seguida do nome da classe ("Rectangle" no seguinte exemplo).

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

Hoisting

- -

Uma diferença importante entre a declaração de funções e a declaração de classes é que a declaração de funções são {{Glossary("Hoisting", "hoisted")}} e a declaração de classes não. É preciso primeiro declarar a classe e só depois aceder-lhe, caso contrário, como no código que se segue, será lançada uma {{jsxref("ReferenceError")}}:

- -
var p = new Rectangle(); // ReferenceError
-
-class Rectangle {}
-
- -

Expressão de Classe

- -

expressão de classe é outra forma de definir uma classe. As expressões de classes podem ter nome o ser anónimas. O nome dado a uma expressão de classe é local ao corpo da classe. (ainda assim pode ser obtido através do propriedade .name da classe (não da instância) )

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

Nota: Expressões de classes também padecem da mesma situação de hoisting mencionada para as declarações de classes.

-
- -

Definição de corpo de classe e de método

- -

O corpo da classe é a parte que está entre as chavetas {}. É aqui que são definidos os membros da classe, tais como, métodos e construtores.

- -

Strict mode - modo estrito

- -

Os corpos da declaração de classes e da expressão de classes são executados em strict mode i.e. construtor, métodos estáticos e de prototipo, funções getter e setter são executadas em modo estrito.

- -

Construtor (constructor)

- -

O método constructor é um método especial para criar e inicializar um objto criado de uma class. Numa classe, apenas pode existir um método especial com o nome "constructor". Se a classe tiver mais do que uma occorrência de um método constructor será lançada uma  {{jsxref("SyntaxError")}}.

- -

Um construtor pode utlizar a palavra reservada super para invocar o construtor da classe pai.

- -

Métodos de Prototype 

- -

Ver também definição de métodos.

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

Métodos estáticos

- -

A palavra reservada static define um método como estático para uma classe. Os métodos estáticos são chamados sem instanciarem as suas classes e não podem ser chamados a partir de instâncias da classe. Os métodos estáticos são frequentemente utilizados para criar funções utilitárias para uma aplicação.

- -
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);
-
-console.log(Point.distance(p1, p2)); // 7.0710678118654755
- -

Boxing com métodos estáticos e de protótipo 

- -

Quando um método estático é chamado sem um objeto correspondente ao "this", o valor do "this" é então undefined dentro do método chamado. O comportamento será o mesmo, mesmo que a diretiva "use strict" não esteja presente, isto porque o código contido no limite sintático do corpo da class é sempre executado em modo estrito.

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

 

- -

Se o texto acima for escrito usando a sintaxe tradicional baseada em função, o autooboxing ocorrerá nas chamadas de método no modo não estrito com base no valor inicial do this. Se o valor inicial for undefined, isso será definido para o objeto global.

- -

Autoboxing não acontecerá no modo estrito, o valor do this permanece como passado ao método.

- -

 

- -
function Animal() { }
-
-Animal.prototype.speak = function() {
-  return this;
-}
-
-Animal.eat = function() {
-  return this;
-}
-
-let obj = new Animal();
-let speak = obj.speak;
-speak(); // global object
-
-let eat = Animal.eat;
-eat(); // global object
- -

Propriedades de instância

- -

Propriedades de instância devem ser definidas dentro de métodos da classe:

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

Propriedades estáticas da classe e propriedades de dados do protótipo devem ser definidas fora da declaração do ClassBody:

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

Declaração de campos (Field)

- -
-

Declarações de campo públicos e privados são uma funcionalidade experimental (stage 3)  proposta no TC39, o comité de padrões JavaScript. O suporte nos navegadores é limitado, mas a funcionalidade pode ser usada por meio de uma etapa de build com sistemas como o Babel.

-
- -

Declaração de campos (field ) públicos

- -

Com a sintaxe de declaração de campo JavaScript, o exemplo acima pode ser escrito como:

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

 

- -

Ao declarar campos antecipadamente, as definições de classe se tornam mais autodocumentadas e os campos estão sempre presentes.

- -

Como visto acima, os campos podem ser declarados com ou sem um valor padrão.

- -

 

- -

Declaração de campos (field) privados 

- -

Usando campos privados, a definição pode ser refinada como abaixo.

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

 

- -

É um erro referenciar campos privados de fora da classe. eles só podem ser lidos ou escritos dentro do corpo da classe. Ao definir coisas que não são visíveis fora da classe, você garante que os utilizadores das suas classes não dependeram de estruturas internas, que podem mudar a versão para a versão.

- -
-

Campos privados só podem ser declarados antecipadamente numa declaração de campo.

-
- -

Os campos privados não podem ser criados posteriormente através da sua afetação, como se pode fazer com as propriedades normais.

- -

 

- -

 

- -

 

- -

 

- -

 

- -

 

- -

Derivação de classes com extends

- -

A palavra reservada extends é utilizada na declaração de classes ou na expressão de classes para criar uma classe filha ou derivada de outra .

- -
class Animal {
-  constructor(name) {
-    this.name = name;
-  }
-
-  speak() {
-    console.log(this.name + ' makes a noise.');
-  }
-}
-
-class Dog extends Animal {
-  speak() {
-    console.log(this.name + ' barks.');
-  }
-}
-
-var d = new Dog('Mitzie');
-d.speak(); // Mitzie barks.
-
- -

Se houver um construtor presente numa classe derivada, este precisa de chamar super() antes de utilizar o "this".

- -

A tradicionais "classes" function-based podem também ser extendidas:

- -
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.');
-  }
-}
-
-var d = new Dog('Mitzie');
-d.speak(); // Mitzie barks.
-
- -

É de notar que uma classe não pode estender um objeto regular (non-constructible). Alternativamente, para se criar herança a partir de um objeto regular, deve ser usado {{jsxref("Object.setPrototypeOf()")}}:

- -
var 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);
-
-var d = new Dog('Mitzie');
-d.speak(); // Mitzie makes a noise.
-
- -

Espécies

- -

Se quiser devolver um objeto do tipo {{jsxref("Array")}} na sua classe derivada MyArray. O padrão espécies permite-lhe redefinir o construtor por omissão.

- -

Por exemplo, na utilização de um método como o {{jsxref("Array.map", "map()")}}, o qual devolve o construtor por omissão, querer-se-á que estes métodos devolvam um objeto pai do tipo Array, em vez de um objeto MyArray. O símbolo {{jsxref("Symbol.species")}} permite fazer isto:

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

Chamadas à super classe com super

- -

A palavra reservada super é utilizada para chamar funções no objeto pai do objeto.

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

Mix-ins

- -

A subclasses abstratas ou mix-ins são templates para classes. Uma classe ECMAScript apenas pode ter uma única superclasse, Portanto, múltiplas heranças de classes de ferramentas, por exemplo, não são possíveis. A funcionalidade deve ser fornecida pela superclasse.

- -

Uma função com uma superclasse como entrada e uma subclasse estendendo aquela superclasse como saída pode ser usada para implementar mix-ins no ECMAScript.:

- -
var calculatorMixin = Base => class extends Base {
-  calc() { }
-};
-
-var randomizerMixin = Base => class extends Base {
-  randomize() { }
-};
-
- -

Uma classe que usa esses mix-ins pode ser escrita assim:

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

Especificações

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES2015', '#sec-class-definitions', 'Class definitions')}}{{Spec2('ES2015')}}Definição inicial.
{{SpecName('ES2016', '#sec-class-definitions', 'Class definitions')}}{{Spec2('ES2016')}} 
{{SpecName('ES2017', '#sec-class-definitions', 'Class definitions')}}{{Spec2('ES2017')}} 
{{SpecName('ESDraft', '#sec-class-definitions', 'Class definitions')}}{{Spec2('ESDraft')}} 
- -

Compatibilidade no Browser 

- - - -

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

- -

Executar no Scratchpad

- -

Uma classe não pode ser redefinida. Se estiver a escrever código no Scratchpad (Firefox menu Tools > Web Developer > Scratchpad) e se 'executar' a definição de uma classe com o mesmo nome duas vezes, irá receber um obscuro SyntaxError: redeclaration of let <class-name>.

- -

Para voltar a executar uma definição, utilise o menu Scratchpad's Execute > Reload and Run.
- Vote, por favor, no bug #1428672.

- -

Veja também

- - diff --git a/files/pt-pt/web/javascript/reference/classes/static/index.html b/files/pt-pt/web/javascript/reference/classes/static/index.html deleted file mode 100644 index 9cb5c48367..0000000000 --- a/files/pt-pt/web/javascript/reference/classes/static/index.html +++ /dev/null @@ -1,131 +0,0 @@ ---- -title: static -slug: Web/JavaScript/Reference/Classes/static -translation_of: Web/JavaScript/Reference/Classes/static ---- -
{{jsSidebar("Classes")}}
- -

A palavra-chave static define um método estático para uma classe.

- -
{{EmbedInteractiveExample("pages/js/classes-static.html")}}
- - - -

Síntaxe

- -
static nomeDoMetodo() { ... }
- -

Descrição

- -

Métodos estáticos são chamados diretamente na classe mas não em instâncias da mesma. Estes são regularmente utilizados para criar funções utilitárias.

- -

Como chamar métodos estáticos

- -

Noutro método estático

- -

Para chamar um método estático dentro de outro que pertença à mesma classe, pode-se usar a palavra-chave this.

- -
class StaticMethodCall {
-  static staticMethod() {
-    return 'Metodo estatico foi invocado';
-  }
-  static anotherStaticMethod() {
-    return this.staticMethod() + ' dentro de outro';
-  }
-}
-StaticMethodCall.staticMethod();
-// 'Metodo estatico foi invocado'
-
-StaticMethodCall.anotherStaticMethod();
-// 'Metodo estatico foi invocado dentro de outro'
- -

No construtor de classe e noutros métodos

- -

Métodos estáticos não são acessíveis através da palavra-chave this quando dentro de métodos não-estáticos. É preciso chamá-los ou através do nome da própria classe: CLASSNAME.STATIC_METHOD_NAME() ou como propriedade do construtor da classe: this.constructor.STATIC_METHOD_NAME().

- -
class StaticMethodCall {
-  constructor() {
-    console.log(StaticMethodCall.staticMethod());
-    // 'metodo estatico foi invocado.'
-
-    console.log(this.constructor.staticMethod());
-    // 'metodo estatico foi invocado.'
-  }
-
-  static staticMethod() {
-    return 'metodo estatico foi invocado.';
-  }
-}
- -

Exemplos

- -

Os seguintes exemplos demonstram:

- -
    -
  1. Como implementar um método estático numa classe.
  2. -
  3. Que se podem criar sub-classes a partir de uma classe com um membro estático (e usá-los).
  4. -
  5. Como se pode chamar um método estático (com contra-exemplos).
  6. -
- -
class Triple {
-  static triple(n) {
-    if (n === undefined) {
-      n = 1;
-    }
-    return n * 3;
-  }
-}
-
-class BiggerTriple extends Triple {
-  static triple(n) {
-    return super.triple(n) * super.triple(n);
-  }
-}
-
-console.log(Triple.triple());        // 3
-console.log(Triple.triple(6));       // 18
-
-var tp = new Triple();
-
-console.log(BiggerTriple.triple(3));
-// 81 (não foi afetado pela instanciação do pai)
-
-console.log(tp.triple());
-// 'tp.triple is not a function'. (não é função)
-
- -

Especificações

- - - - - - - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName('ES2015', '#sec-class-definitions', 'Definições de Classe')}}{{Spec2('ES2015')}}Definição inicial.
{{SpecName('ESDraft', '#sec-class-definitions', 'Definições de Classe')}}{{Spec2('ESDraft')}} 
- -

Compatibilidade de browsers

- - - -

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

- -

Ver também

- - diff --git a/files/pt-pt/web/javascript/reference/deprecated_and_obsolete_features/index.html b/files/pt-pt/web/javascript/reference/deprecated_and_obsolete_features/index.html deleted file mode 100644 index db64832bf4..0000000000 --- a/files/pt-pt/web/javascript/reference/deprecated_and_obsolete_features/index.html +++ /dev/null @@ -1,290 +0,0 @@ ---- -title: Funcionalidades obsoletas -slug: Web/JavaScript/Reference/Deprecated_and_obsolete_features -tags: - - JavaScript - - Obsoleto -translation_of: Web/JavaScript/Reference/Deprecated_and_obsolete_features -original_slug: Web/JavaScript/Reference/Funcionalidades_obsoletas ---- -
{{JsSidebar("More")}}
- -

Esta página lista as funcionalidades de JavaScript que estão obsoletas (ou seja, ainda disponíveis, mas planeadas para remoção) e obsoletas (isto é, não são mais utilizáveis).

- -

Funcionalidades obsoletas

- -

Estas funcionalidades obsoletas ainda podem ser utilziadas, mas devem ser utilizadas ​​com cuidado, pois espera-se que estas sejam removidas inteiramente no futuro. Deverá trabalhar para remover a utilização das mesmas do seu código..

- -

Propriedades de RegExp

- -

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

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
PropriedadesDescrição
{{jsxref("RegExp.n", "$1-$9")}} -

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

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

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

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

Métodos de egExp

- - - -

Propriedades de Function

- - - -

Gerador de Legacy

- - - -

Iterator

- - - -

Métodos de Object

- - - -

Métodos de Date

- - - -

Functions

- - - -

Proxy

- - - -

Sequências de Escape

- - - -

Métodos de String

- - - -

Funcionalidades removidas

- -

Estas funcionalidades obsoletas foram totalmente removidas do JavaScript e não podem mais ser utilizadas a partir da versão indicada do JavaScript.

- -

Object

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

Function

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

Array

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

Number

- - - -

ParallelArray

- - - -

Statements

- - - -

E4X

- -

See E4X for more information.

- -

Variáveis Sharp

- -

Consulte Sharp variables in JavaScript para mais informação.

diff --git a/files/pt-pt/web/javascript/reference/errors/index.html b/files/pt-pt/web/javascript/reference/errors/index.html deleted file mode 100644 index c295fccea6..0000000000 --- a/files/pt-pt/web/javascript/reference/errors/index.html +++ /dev/null @@ -1,31 +0,0 @@ ---- -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/pt-pt/web/javascript/reference/errors/not_a_function/index.html b/files/pt-pt/web/javascript/reference/errors/not_a_function/index.html deleted file mode 100644 index e17857e074..0000000000 --- a/files/pt-pt/web/javascript/reference/errors/not_a_function/index.html +++ /dev/null @@ -1,172 +0,0 @@ ---- -title: 'TypeError: "x" is not a function' -slug: Web/JavaScript/Reference/Errors/Not_a_function -tags: - - Erro - - Erros - - JavaScript - - TypeError -translation_of: Web/JavaScript/Reference/Errors/Not_a_function ---- -
{{jsSidebar("Errors")}}
- -

A exeção de JavaScript "is not a function" ocorre quando há uma tentativa de chamar um valor a partir de uma função, mas o valor não é uma função.

- -

Mensagem

- -
TypeError: Object doesn't support property or method {x} (Edge)
-TypeError: "x" is not a function
-
- -

Tipo de erro

- -

{{jsxref("TypeError")}}

- -

O que deu errado?

- -

Tentou chamar um valor a partir de uma função, mas o valor não é uma função. Isto acontece quando algum código espera que se forneça uma função, mas isso não acontece.

- -

Talvez haja um erro no nome da função? Pode ser que o objeto a que está a chamar o método não tenha esta função? Por exemplo, um Object não tem função de map, mas o Array tem.

- -

Há muitas funções que necessitam de uma função como parâmetro (callback). Terá de fornecer uma função para que estes métodos funcionem corretamente:

- - - -

Exemplos

- -

Um erro no nome da função

- -

Neste caso existe um erro no nome função:

- -
let x = document.getElementByID('foo');
-// TypeError: document.getElementByID is not a function
-
- -

O nome correto da função é getElementById:

- -
let x = document.getElementById('foo');
-
- -

Função é chamada no objeto errado

- -

Para certos métodos, é necessário fornecer uma função (callback) e funcionará apenas em objetos específicos. Neste exemplo, é utilizado o {{jsxref("Array.prototype.map()")}}, que funcionará apenas com objetos {{jsxref("Array")}}.

- -
let obj = {a: 13, b: 37, c: 42};
-
-obj.map(function(num) {
-  return num * 2;
-});
-
-// TypeError: obj.map is not a function
- -

Use antes uma matriz:

- -
let numbers = [1, 4, 9];
-
-numbers.map(function(num) {
-  return num * 2;
-});
-
-// Array [2, 8, 18]
-
- -

Function shares a name with a pre-existing property

- -

Por vezes, ao criar uma classe, pode ter uma propriedade e uma função com o mesmo nome. Ao chamar a função, o compilador pensa que a função deixa de existir.

- -
var Dog = function () {
- this.age = 11;
- this.color = "black";
- this.name = "Ralph";
- return this;
-}
-
-Dog.prototype.name = function(name) {
- this.name = name;
- return this;
-}
-
-
-var myNewDog = new Dog();
-myNewDog.name("Cassidy"); //Uncaught TypeError: myNewDog.name is not a function
-
- -

Use um nome diferente para a propriedade:

- -
var Dog = function () {
- this.age = 11;
- this.color = "black";
- this.dogName = "Ralph"; //Using this.dogName instead of .name
- return this;
-}
-
-Dog.prototype.name = function(name) {
- this.dogName = name;
- return this;
-}
-
-
-var myNewDog = new Dog();
-myNewDog.name("Cassidy"); //Dog { age: 11, color: 'black', dogName: 'Cassidy' }
-
- -

Usar parênteses para multiplicação

- -

Em matemática, pode escrever 2 × (3 + 5) como 2*(3 + 5) ou somente 2(3 + 5).

- -

Usar a última forma dá um erro:

- -
const sixteen = 2(3 + 5);
-alert('2 x (3 + 5) is ' + String(sixteen));
-//Uncaught TypeError: 2 is not a function
- -

Pode corrigir o erro com a operadora *:

- -
const sixteen = 2 * (3 + 5);
-alert('2 x (3 + 5) is ' + String(sixteen));
-//2 x (3 + 5) is 16
-
- -

Importar o modulo exportado corretamente

- -

Certifique-se que está a importar o módulo corretamente.

- -

Um exemplo de uma biblioteca helper (helpers.js)

- -
let helpers = function () { };
-
-helpers.groupBy = function (objectArray, property) {
-  return objectArray.reduce(function (acc, obj) {
-    var key = obj[property];
-    if (!acc[key]) {
-      acc[key] = [];
-    }
-    acc[key].push(obj);
-    return acc;
-  },
-{});
-}
-
-export default helpers;
-
- -

A utilização correta de importação (para App.js) é:

- -
import helpers from './helpers'
- -

Ver também

- - diff --git a/files/pt-pt/web/javascript/reference/errors/stmt_after_return/index.html b/files/pt-pt/web/javascript/reference/errors/stmt_after_return/index.html deleted file mode 100644 index f3d1de92c8..0000000000 --- a/files/pt-pt/web/javascript/reference/errors/stmt_after_return/index.html +++ /dev/null @@ -1,77 +0,0 @@ ---- -title: 'Aviso: código inacessível depois de declaração de retorno' -slug: Web/JavaScript/Reference/Errors/Stmt_after_return -tags: - - Aviso - - JavaScript -translation_of: Web/JavaScript/Reference/Errors/Stmt_after_return ---- -
{{jsSidebar("Errors")}}
- -

Mensagem

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

Tipo de ErroEdit

- -

Aviso

- -

O que correu mal?Edit

- -

Unreachable code after return statement pode ocorrer nas seguintes situações:

- - - -

Quando existe uma expressão depois de uma declaração return válida, é dado um aviso para indicar que o código depois da declaração return é inacessível, o que significa que o mesmo nunca pode ser executado.

- -

Porquê é que eu deveria ter ponto e vírgula depois de declarações return? No caso de declarações return sem ponto e vírgula, não é claro se o programador pretendia devolver a declaração na linha seguinte, ou para parar a execução e o retorno. O aviso indica que existe ambiguidade no modo como a declaração return foi escrita.

- -

Os avisos não serão apresentados para declarações return sem ponto-e-vírgula nas seguintes situações:

- - - -

Exemplos

- -

Casos inválidos

- -
function f() {
-  var x = 3;
-  x += 4;
-  return x;   // retorna a função de imediato
-  x -= 3;     // logo, esta linha não será executada; é inacessivel
-}
-
-function f() {
-  return     // é tratado como um `return;`
-    3 + 4;   // logo, a função é retornada, porém esta linha não será alcançada
-}
-
- -

Casos válidos

- -
function f() {
-  var x = 3;
-  x += 4;
-  x -= 3;
-  return x;  // OK: return depois de todas as declarações
-}
-
-function f() {
-  return 3 + 4  // OK: um return sem ponto e vírgula com uma expressão na mesma linha
-}
-
- -

Consulte tambémEdit

- - diff --git a/files/pt-pt/web/javascript/reference/errors/unexpected_token/index.html b/files/pt-pt/web/javascript/reference/errors/unexpected_token/index.html deleted file mode 100644 index 55103f82a7..0000000000 --- a/files/pt-pt/web/javascript/reference/errors/unexpected_token/index.html +++ /dev/null @@ -1,50 +0,0 @@ ---- -title: 'SyntaxError: Unexpected token' -slug: Web/JavaScript/Reference/Errors/Unexpected_token -tags: - - Erro de Sintaxe - - Erros - - JavaScript -translation_of: Web/JavaScript/Reference/Errors/Unexpected_token ---- -
{{jsSidebar("Errors")}}
- -

Mensagem

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

Tipo de erro

- -

{{jsxref("SyntaxError")}}

- -

O que aconteceu de errado?

- -

É esperado um contrutor de linguagem específico, mas foi entregue outra coisa qualquer. Isto poderá ser simplesmente um erro de escrita.

- -

Exemplos

- -

Expressão esperada

- -

Por exemplo, quando são chamadas funções, as vírgulas  imediatamente antes de fechar a função não são permitidas. JavaScript vai esperar outro argumento, que pode na verdade ser qualquer expressão.

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

Para corrigir o problema, retirava-se a virgula ou adicionavam-se mais argumentos:

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

Veja também

- - diff --git a/files/pt-pt/web/javascript/reference/errors/unnamed_function_statement/index.html b/files/pt-pt/web/javascript/reference/errors/unnamed_function_statement/index.html deleted file mode 100644 index 25a542b9df..0000000000 --- a/files/pt-pt/web/javascript/reference/errors/unnamed_function_statement/index.html +++ /dev/null @@ -1,114 +0,0 @@ ---- -title: 'Erro de sintaxe: declaração de função precisa de um nome' -slug: Web/JavaScript/Reference/Errors/Unnamed_function_statement -translation_of: Web/JavaScript/Reference/Errors/Unnamed_function_statement -original_slug: Web/JavaScript/Reference/Errors/declaração_função_sem_nome ---- -
{{jsSidebar("Errors")}}
- -

Mensagem

- -
Syntax Error: Expected identifier (Edge)
-SyntaxError: function statement requires a name [Firefox]
-SyntaxError: Unexpected token ( [Chrome]
-
- -

Tipo de erro

- -

{{jsxref("SyntaxError")}}

- -

O que correu mal?

- -

Existe uma declaração de função no código que precisa de um nome. Você deve verficiar como as funções são definidas e se é necessário indicar um nome para a função

- -

Existe uma declaração de função no código que requer um nome. Você precisará verificar como as funções são definidas e se você precisa fornecer um nome para a função, ou se a função em questão precisa ser uma expressão de função, um {{Glossary ("IIFE")}}, ou se o código da função esta colocado corretamente neste contexto.

- -

Exemplos

- -

Declarações vs Expressões

- -

Uma declaração de função precisa de um nome, o código seguinte não funciona:

- -
function () {
-  return 'Hello world';
-}
-// SyntaxError: function statement requires a name
-
- -

É possível usar uma expressão de função (atribuição) como alternativa:

- -
var greet = function() {
-  return 'Hello world';
-};
- -

Ou, a sua função é talvez destinada a ser uma IIFE (Expressão de Função Invocada Imediatamente), que é uma função que é executada assim que é definida. Serão precisos mais alguns parêntises neste caso:

- -
(function () {
-
-})();
- -

Funções com nome

- -

Se você está a usar uma função com identificador, ainda precisará fornecer um nome de função após a palavra-chave da função. O código seguinte não funciona:

- -
function Greeter() {
-  german: function () {
-    return "Moin";
-  }
-}
-// SyntaxError: function statement requires a name
-
- -

O código seguinte irá funcionar por exemplo:

- -
function Greeter() {
-  german: function g() {
-    return "Moin";
-  }
-}
- -

Métodos de objectos

- -

Se você pretendia criar um método de um objeto, você precisará criar um objeto. A sintaxe a seguir sem um nome após a palavra-chave function é válida.

- -
var greeter = {
-  german: function () {
-    return "Moin";
-  }
-};
- -

Sintaxe de Callback

- -

Além disso, verifique a sintaxe ao usar callbacks. Parêntisis e virgurlas podem facilmente se tornar complicados.

- -
promise.then(
-  function() {
-    console.log("success");
-  });
-  function() {
-    console.log("error");
-}
-// SyntaxError: function statement requires a name
-
- -

:

- -
promise.then(
-  function() {
-    console.log("success");
-  },
-  function() {
-    console.log("error");
-  }
-);
-
- -

Veja também

- - diff --git a/files/pt-pt/web/javascript/reference/functions/arguments/index.html b/files/pt-pt/web/javascript/reference/functions/arguments/index.html deleted file mode 100644 index 01c656de88..0000000000 --- a/files/pt-pt/web/javascript/reference/functions/arguments/index.html +++ /dev/null @@ -1,229 +0,0 @@ ---- -title: O objeto arguments -slug: Web/JavaScript/Reference/Functions/arguments -tags: - - Class - - Funções - - JavaScript - - Referencia - - arguments -translation_of: Web/JavaScript/Reference/Functions/arguments -original_slug: Web/JavaScript/Reference/Funcoes/arguments ---- -

{{JSSidebar("Functions")}}

- -

arguments é um objeto semelhante a uma "Matiz" acessível dentro de functions que contém os valores dos argumentos passados ​​para essa função.

- -
-

Nota: If you're writing ES6 compatible code, then rest parameters should be preferred.

-
- -
-

Nota: “Array-like” means that arguments has a length property and properties indexed from zero, but it doesn't have {{JSxRef("Array")}}'s built-in methods like forEach and map. See §Description for details.

-
- -
{{EmbedInteractiveExample("pages/js/functions-arguments.html")}}
- - - -

Sintaxe

- -
arguments
- -

Descrição

- -

The arguments object is a local variable available within all non-arrow functions. You can refer to a function's arguments inside that function by using its arguments object. It has entries for each argument the function was called with, with the first entry's index at 0.

- -

For example, if a function is passed 3 arguments, you can access them as follows:

- -
arguments[0] // first argument
-arguments[1] // second argument
-arguments[2] // third argument
-
- -

Each argument can also be set or reassigned:

- -
arguments[1] = 'new value';
-
- -

The arguments object is not an {{JSxRef("Array")}}. It is similar, but does not have any Array properties except length. For example, it does not have the pop method. However, it can be converted to a real Array:

- -
var args = Array.prototype.slice.call(arguments);
-// Using an array literal is shorter than above but allocates an empty array
-var args = [].slice.call(arguments);
-
- -

As you can do with any Array-like object, you can use ES2015's {{JSxRef("Array.from()")}} method or spread operator to convert arguments to a real Array:

- -
let args = Array.from(arguments);
-// or
-let args = [...arguments];
- -

The arguments object is useful for functions called with more arguments than they are formally declared to accept. This technique is useful for functions that can be passed a variable number of arguments, such as Math.min(). This example function accepts any number of string arguments and returns the longest one:

- -
function longestString() {
-  var longest = '';
-  for (var i=0; i < arguments.length; i++) {
-    if (arguments[i].length > longest.length) {
-      longest = arguments[i];
-    }
-  }
-  return longest;
-}
-
- -

You can use arguments.length to count how many arguments the function was called with. If you instead want to count how many parameters a function is declared to accept, inspect that function's length property.

- -

Utilizar typeof com Arguments

- -

The typeof operator returns 'object' when used with arguments

- -
console.log(typeof arguments); // 'object' 
- -

The type of individual arguments can be determined by indexing arguments:

- -
console.log(typeof arguments[0]); // returns the type of the first argument
- -

Propriedades

- -
-
-
{{jsxref("Functions/arguments/callee", "arguments.callee")}}
-
Reference to the currently executing function that the arguments belong to.
-
{{jsxref("Functions/arguments/length", "arguments.length")}}
-
The number of arguments that were passed to the function.
-
{{jsxref("Functions/arguments/@@iterator", "arguments[@@iterator]")}}
-
Returns a new {{jsxref("Array/@@iterator", "Array iterator", "", 0)}} object that contains the values for each index in arguments.
-
- -

Exemplos

- -

Definir uma function que concatena várias strings

- -

This example defines a function that concatenates several strings. The function's only formal argument is a string containing the characters that separate the items to concatenate.

- -
function myConcat(separator) {
-  var args = Array.prototype.slice.call(arguments, 1);
-  return args.join(separator);
-}
- -

You can pass as many arguments as you like to this function. It returns a string list using each argument in the list:

- -
// returns "red, orange, blue"
-myConcat(', ', 'red', 'orange', 'blue');
-
-// returns "elephant; giraffe; lion; cheetah"
-myConcat('; ', 'elephant', 'giraffe', 'lion', 'cheetah');
-
-// returns "sage. basil. oregano. pepper. parsley"
-myConcat('. ', 'sage', 'basil', 'oregano', 'pepper', 'parsley');
- -

Definir uma function que cria listas HTML

- -

This example defines a function that creates a string containing HTML for a list. The only formal argument for the function is a string that is "u" if the list is to be unordered (bulleted), or "o" if the list is to be ordered (numbered). The function is defined as follows:

- -
function list(type) {
-  var html = '<' + type + 'l><li>';
-  var args = Array.prototype.slice.call(arguments, 1);
-  html += args.join('</li><li>');
-  html += '</li></' + type + 'l>'; // end list
-
-  return html;
-}
- -

You can pass any number of arguments to this function, and it adds each argument as a list item to a list of the type indicated. For example:

- -
var listHTML = list('u', 'One', 'Two', 'Three');
-
-/* listHTML is:
-"<ul><li>One</li><li>Two</li><li>Three</li></ul>"
-*/
- -

Parâmetros Rest, predefinição, e desestruturados

- -

The arguments object can be used in conjunction with rest, default, and destructured parameters.

- -
function foo(...args) {
-  return args;
-}
-foo(1, 2, 3); // [1,2,3]
-
- -

While the presence of rest, default, or destructured parameters does not alter the behavior of the arguments object in strict mode code, there is a subtle difference for non-strict code.

- -

In strict-mode code, the arguments object behaves the same whether or not a function is passed rest, default, or destructured parameters. That is, assigning new values to variables in the body of the function will not affect the arguments object. Nor will assigning new variables to the arguments object affect the value of variables.

- -
-

Nota: You cannot write a "use strict"; directive in the body of a function definition that accepts rest, default, or destructured parameters. Doing so will throw a syntax error.

-
- -

Non-strict functions that are passed only simple parameters (that is, not rest, default, or restructured parameters) will sync the value of variables new values in the body of the function with the arguments object, and vice versa:

- -
function func(a) {
-  arguments[0] = 99; // updating arguments[0] also updates a
-  console.log(a);
-}
-func(10); // 99
-
- -

And also:

- -
function func(a) {
-  a = 99; // updating a also updates arguments[0]
-  console.log(arguments[0]);
-}
-func(10); // 99
-
- -

Conversely, non-strict functions that are passed rest, default, or destructured parameters will not sync new values assigned to argument variables in the function body with the arguments object. Instead, the arguments object in non-strict functions with complex parameters will always reflect the values passed to the function when the function was called (this is the same behavior as exhibited by all strict-mode functions, regardless of the type of variables they are passed):

- -
function func(a = 55) {
-  arguments[0] = 99; // updating arguments[0] does not also update a
-  console.log(a);
-}
-func(10); // 10
- -

E também:

- -
function func(a = 55) {
-  a = 99; // updating a does not also update arguments[0]
-  console.log(arguments[0]);
-}
-func(10); // 10
-
- -

E também:

- -
// An untracked default parameter
-function func(a = 55) {
-  console.log(arguments[0]);
-}
-func(); // undefined
- -

Especificações

- - - - - - - - - - - - -
Especificação
{{SpecName('ESDraft', '#sec-arguments-exotic-objects', 'Arguments Exotic Objects')}}
- -

Compatibildiade de navegador

- - - -

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

- -

Consulte também

- - diff --git a/files/pt-pt/web/javascript/reference/functions/arrow_functions/index.html b/files/pt-pt/web/javascript/reference/functions/arrow_functions/index.html deleted file mode 100644 index 1a2246534b..0000000000 --- a/files/pt-pt/web/javascript/reference/functions/arrow_functions/index.html +++ /dev/null @@ -1,400 +0,0 @@ ---- -title: Expressões da função "Seta" -slug: Web/JavaScript/Reference/Functions/Arrow_functions -translation_of: Web/JavaScript/Reference/Functions/Arrow_functions -original_slug: Web/JavaScript/Reference/Funcoes/Funcoes_seta ---- -
{{jsSidebar("Functions")}}
- -

Uma expressão da função seta é uma alternativa sintaticamente compacta a uma expressão de expressão de função regular, embora sem as suas próprias associações às palavras-chave this, arguments, super, ou new.target. As expressões de função (function) de seta são inadequadas como métodos, e não podem ser utilziadas como construtores.

- -
{{EmbedInteractiveExample("pages/js/functions-arrow.html")}}
- -

Sintaxe

- -

Basic syntax

- -
(param1, param2, …, paramN) => { statements }
-(param1, param2, …, paramN) => expression
-// equivalent to: => { return expression; }
-
-// Parentheses are optional when there's only one parameter name:
-(singleParam) => { statements }
-singleParam => { statements }
-
-// The parameter list for a function with no parameters should be written with a pair of parentheses.
-() => { statements }
-
- -

Advanced syntax

- -
// Parenthesize the body of a function to return an object literal expression:
-params => ({foo: bar})
-
-// Rest parameters and default parameters are supported
-(param1, param2, ...rest) => { statements }
-(param1 = defaultValue1, param2, …, paramN = defaultValueN) => {
-statements }
-
-// Destructuring within the parameter list is also supported
-var f = ([a, b] = [1, 2], {x: c} = {x: a + b}) => a + b + c;
-f(); // 6
-
- -

Descrição

- -

See also "ES6 In Depth: Arrow functions" on hacks.mozilla.org.

- -

Two factors influenced the introduction of arrow functions: the need for shorter functions and the behavior of the this keyword.

- -

Funções curtas

- -
var elements = [
-  'Hydrogen',
-  'Helium',
-  'Lithium',
-  'Beryllium'
-];
-
-// This statement returns the array: [8, 6, 7, 9]
-elements.map(function(element) {
-  return element.length;
-});
-
-// The regular function above can be written as the arrow function below
-elements.map((element) => {
-  return element.length;
-}); // [8, 6, 7, 9]
-
-// When there is only one parameter, we can remove the surrounding parentheses
-elements.map(element => {
-  return element.length;
-}); // [8, 6, 7, 9]
-
-// When the only statement in an arrow function is `return`, we can remove `return` and remove
-// the surrounding curly brackets
-elements.map(element => element.length); // [8, 6, 7, 9]
-
-// In this case, because we only need the length property, we can use destructuring parameter:
-// Notice that the `length` corresponds to the property we want to get whereas the
-// obviously non-special `lengthFooBArX` is just the name of a variable which can be changed
-// to any valid variable name you want
-elements.map(({ length: lengthFooBArX }) => lengthFooBArX); // [8, 6, 7, 9]
-
-// This destructuring parameter assignment can also be written as seen below. However, note that in
-// this example we are not assigning `length` value to the made up property. Instead, the literal name
-// itself of the variable `length` is used as the property we want to retrieve from the object.
-elements.map(({ length }) => length); // [8, 6, 7, 9]
-
- -

No separate this

- -

Before arrow functions, every new function defined its own this value based on how the function was called:

- - - -

This proved to be less than ideal with an object-oriented style of programming.

- -
function Person() {
-  // The Person() constructor defines `this` as an instance of itself.
-  this.age = 0;
-
-  setInterval(function growUp() {
-    // In non-strict mode, the growUp() function defines `this`
-    // as the global object (because it's where growUp() is executed.),
-    // which is different from the `this`
-    // defined by the Person() constructor.
-    this.age++;
-  }, 1000);
-}
-
-var p = new Person();
- -

In ECMAScript 3/5, the this issue was fixable by assigning the value in this to a variable that could be closed over.

- -
function Person() {
-  var that = this;
-  that.age = 0;
-
-  setInterval(function growUp() {
-    // The callback refers to the `that` variable of which
-    // the value is the expected object.
-    that.age++;
-  }, 1000);
-}
- -

Alternatively, a bound function could be created so that a preassigned this value would be passed to the bound target function (the growUp() function in the example above).

- -

An arrow function does not have its own this. The this value of the enclosing lexical scope is used; arrow functions follow the normal variable lookup rules. So while searching for this which is not present in current scope, an arrow function ends up finding the this from its enclosing scope.

- -

Thus, in the following code, the this within the function that is passed to setInterval has the same value as the this in the lexically enclosing function:

- -
function Person(){
-  this.age = 0;
-
-  setInterval(() => {
-    this.age++; // |this| properly refers to the Person object
-  }, 1000);
-}
-
-var p = new Person();
- -

Relation with strict mode

- -

Given that this comes from the surrounding lexical context, strict mode rules with regard to this are ignored.

- -
var f = () => { 'use strict'; return this; };
-f() === window; // or the global object
- -

All other strict mode rules apply normally.

- -

Invoked through call or apply

- -

Since arrow functions do not have their own this, the methods call() and apply() can only pass in parameters. Any this argument is ignored.

- -
var adder = {
-  base: 1,
-
-  add: function(a) {
-    var f = v => v + this.base;
-    return f(a);
-  },
-
-  addThruCall: function(a) {
-    var f = v => v + this.base;
-    var b = {
-      base: 2
-    };
-
-    return f.call(b, a);
-  }
-};
-
-console.log(adder.add(1));         // This would log 2
-console.log(adder.addThruCall(1)); // This would log 2 still
- -

No binding of arguments

- -

Arrow functions do not have their own arguments object. Thus, in this example, arguments is simply a reference to the arguments of the enclosing scope:

- -
var arguments = [1, 2, 3];
-var arr = () => arguments[0];
-
-arr(); // 1
-
-function foo(n) {
-  var f = () => arguments[0] + n; // foo's implicit arguments binding. arguments[0] is n
-  return f();
-}
-
-foo(3); // 6
- -

In most cases, using rest parameters is a good alternative to using an arguments object.

- -
function foo(n) {
-  var f = (...args) => args[0] + n;
-  return f(10);
-}
-
-foo(1); // 11
- -

Arrow functions used as methods

- -

As stated previously, arrow function expressions are best suited for non-method functions. Let's see what happens when we try to use them as methods:

- -
'use strict';
-
-var obj = { // does not create a new scope
-  i: 10,
-  b: () => console.log(this.i, this),
-  c: function() {
-    console.log(this.i, this);
-  }
-}
-
-obj.b(); // prints undefined, Window {...} (or the global object)
-obj.c(); // prints 10, Object {...}
- -

Arrow functions do not have their own this. Another example involving {{jsxref("Object.defineProperty()")}}:

- -
'use strict';
-
-var obj = {
-  a: 10
-};
-
-Object.defineProperty(obj, 'b', {
-  get: () => {
-    console.log(this.a, typeof this.a, this); // undefined 'undefined' Window {...} (or the global object)
-    return this.a + 10; // represents global object 'Window', therefore 'this.a' returns 'undefined'
-  }
-});
-
- -

Use of the new operator

- -

Arrow functions cannot be used as constructors and will throw an error when used with new.

- -
var Foo = () => {};
-var foo = new Foo(); // TypeError: Foo is not a constructor
- -

Use of prototype property

- -

Arrow functions do not have a prototype property.

- -
var Foo = () => {};
-console.log(Foo.prototype); // undefined
-
- -

Use of the yield keyword

- -

The yield keyword may not be used in an arrow function's body (except when permitted within functions further nested within it). As a consequence, arrow functions cannot be used as generators.

- -

Function body

- -

Arrow functions can have either a "concise body" or the usual "block body".

- -

In a concise body, only an expression is specified, which becomes the implicit return value. In a block body, you must use an explicit return statement.

- -
var func = x => x * x;
-// concise body syntax, implied "return"
-
-var func = (x, y) => { return x + y; };
-// with block body, explicit "return" needed
-
- -

Returning object literals

- -

Keep in mind that returning object literals using the concise body syntax params => {object:literal} will not work as expected.

- -
var func = () => { foo: 1 };
-// Calling func() returns undefined!
-
-var func = () => { foo: function() {} };
-// SyntaxError: function statement requires a name
- -

This is because the code inside braces ({}) is parsed as a sequence of statements (i.e. foo is treated like a label, not a key in an object literal).

- -

You must wrap the object literal in parentheses:

- -
var func = () => ({ foo: 1 });
- -

Line breaks

- -

An arrow function cannot contain a line break between its parameters and its arrow.

- -
var func = (a, b, c)
-  => 1;
-// SyntaxError: expected expression, got '=>'
- -

However, this can be amended by putting the line break after the arrow or using parentheses/braces as seen below to ensure that the code stays pretty and fluffy. You can also put line breaks between arguments.

- -
var func = (a, b, c) =>
-  1;
-
-var func = (a, b, c) => (
-  1
-);
-
-var func = (a, b, c) => {
-  return 1
-};
-
-var func = (
-  a,
-  b,
-  c
-) => 1;
-
-// no SyntaxError thrown
- -

Parsing order

- -

Although the arrow in an arrow function is not an operator, arrow functions have special parsing rules that interact differently with operator precedence compared to regular functions.

- -
let callback;
-
-callback = callback || function() {}; // ok
-
-callback = callback || () => {};
-// SyntaxError: invalid arrow-function arguments
-
-callback = callback || (() => {});    // ok
-
- -

More examples

- -
// An empty arrow function returns undefined
-let empty = () => {};
-
-(() => 'foobar')();
-// Returns "foobar"
-// (this is an Immediately Invoked Function Expression)
-
-var simple = a => a > 15 ? 15 : a;
-simple(16); // 15
-simple(10); // 10
-
-let max = (a, b) => a > b ? a : b;
-
-// Easy array filtering, mapping, ...
-
-var arr = [5, 6, 13, 0, 1, 18, 23];
-
-var sum = arr.reduce((a, b) => a + b);
-// 66
-
-var even = arr.filter(v => v % 2 == 0);
-// [6, 0, 18]
-
-var double = arr.map(v => v * 2);
-// [10, 12, 26, 0, 2, 36, 46]
-
-// More concise promise chains
-promise.then(a => {
-  // ...
-}).then(b => {
-  // ...
-});
-
-// Parameterless arrow functions that are visually easier to parse
-setTimeout( () => {
-  console.log('I happen sooner');
-  setTimeout( () => {
-    // deeper code
-    console.log('I happen later');
-  }, 1);
-}, 1);
-
- -

Specifications

- - - - - - - - - - -
Specification
{{SpecName('ESDraft', '#sec-arrow-function-definitions', 'Arrow Function Definitions')}}
- -

Browser compatibility

- -
- - -

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

-
- -

See also

- - diff --git a/files/pt-pt/web/javascript/reference/functions/index.html b/files/pt-pt/web/javascript/reference/functions/index.html deleted file mode 100644 index b77d914f53..0000000000 --- a/files/pt-pt/web/javascript/reference/functions/index.html +++ /dev/null @@ -1,595 +0,0 @@ ---- -title: Funções -slug: Web/JavaScript/Reference/Functions -tags: - - Constructor - - Função - - Funções - - JavaScript - - Parâmetro - - parâmetros -translation_of: Web/JavaScript/Reference/Functions -original_slug: Web/JavaScript/Reference/Funcoes ---- -
{{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.

- -

Descrição

- -

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.

- -

Definindo funções

- -

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.

- -

Parâmetros de função

- -

Parâmetros predefinidos

- -

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.

- -

Parâmetros Rest

- -

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

- -

O objeto arguments

- -

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

- - - -

Definindo funções de método

- -

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

Constructor vs. declaration vs. 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.");
-   };
-}
-
- -

Exemplos

- -

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.

- -

Especificações

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

Compatibilidade de navegador

- - - -

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

- -

Consulte também

- - diff --git a/files/pt-pt/web/javascript/reference/functions/rest_parameters/index.html b/files/pt-pt/web/javascript/reference/functions/rest_parameters/index.html deleted file mode 100644 index 357ce41efa..0000000000 --- a/files/pt-pt/web/javascript/reference/functions/rest_parameters/index.html +++ /dev/null @@ -1,235 +0,0 @@ ---- -title: Parâmetros Rest -slug: Web/JavaScript/Reference/Functions/rest_parameters -tags: - - Funcionalidade Linguagem - - Funções - - JavaScript - - Parametros Rest - - Rest -translation_of: Web/JavaScript/Reference/Functions/rest_parameters -original_slug: Web/JavaScript/Reference/Funcoes/parametros_rest ---- -
Parâmetrois {{jsSidebar("Functions")}}
- -

A sintaxe do parâmetro "rest" permite-nos representar um número indefinido de argumentoscomo um array.

- -
{{EmbedInteractiveExample("pages/js/functions-restparameters.html")}}
- - - -

Sintaxe

- -
function f(a, b, ...theArgs) {
-  // ...
-}
- -

Descrição

- -

A function's last parameter can be prefixed with ... which will cause all remaining (user supplied) arguments to be placed within a "standard" Javascript array.

- -

Only the last parameter can be a "rest parameter".

- -
function myFun(a, b, ...manyMoreArgs) {
-  console.log("a", a)
-  console.log("b", b)
-  console.log("manyMoreArgs", manyMoreArgs)
-}
-
-myFun("one", "two", "three", "four", "five", "six")
-
-// Console Output:
-// a, one
-// b, two
-// manyMoreArgs, [three, four, five, six]
-
- -

Difference between rest parameters and the arguments object

- -

There are three main differences between rest parameters and the {{jsxref("Functions/arguments", "arguments")}} object:

- - - -

From arguments to an array

- -

Rest parameters have been introduced to reduce the boilerplate code that was induced by the arguments

- -
// Before rest parameters, "arguments" could be converted to a normal array using:
-
-function f(a, b) {
-
-  let normalArray = Array.prototype.slice.call(arguments)
-  // -- or --
-  let normalArray = [].slice.call(arguments)
-  // -- or --
-  let normalArray = Array.from(arguments)
-
-  let first = normalArray.shift()  // OK, gives the first argument
-  let first = arguments.shift()    // ERROR (arguments is not a normal array)
-}
-
-// Now, you can easily gain access to a normal array using a rest parameter
-
-function f(...args) {
-  let normalArray = args
-  let first = normalArray.shift() // OK, gives the first argument
-}
-
- -

Destructuring rest parameters

- -

Rest parameters can be destructured Arrays only (though objects will soon be supported). That means that their data can be unpacked into distinct variables. (See Destructuring assignment.)

- -
function f(...[a, b, c]) {
-  return a + b + c;
-}
-
-f(1)          // NaN (b and c are undefined)
-f(1, 2, 3)    // 6
-f(1, 2, 3, 4) // 6 (the fourth parameter is not destructured)
-
- -
-

Fixme

- -

Doing this is possible, but (afaik) there's no use-case, so it's just confusing the junior audience. The following code does exactly the same. There should at least be a note, that in theory you can do something like this, but there is no point in doing so. The example is contrived, but imagine that [a, b, c] were the return value of some function. Then the utility is clear.

- -

Also, since Function arguments will never have named parameters (this is not Python), the statement "objects will soon be supported" is wrong. The preceding example may be mixing up destructuring with rest parameters. Please see the page on destructuring assignment for an example with object destructuring applied in the parameters area.

- -
function f(a, b, c) {
-  return a + b + c
-}
-
-f(1)          // NaN (b and c are undefined)
-f(1, 2, 3)    // 6
-f(1, 2, 3, 4) // 6 (the fourth parameter is not ...)
-
-
- -

Exemplos

- -

In this example, the first argument is mapped to a and the second to b, so these named arguments are used like normal.

- -

However, the third argument, manyMoreArgs, will be an array that contains the 3rd, 4th, 5th, 6th ... nth — as many arguments that the user includes.

- -
function myFun(a, b, ...manyMoreArgs) {
-  console.log("a", a)
-  console.log("b", b)
-  console.log("manyMoreArgs", manyMoreArgs)
-}
-
-myFun("one", "two", "three", "four", "five", "six")
-
-// a, one
-// b, two
-// manyMoreArgs, [three, four, five, six]
-
- -

Below... even though there is just one value, the last argument still gets put into an array.

- -
// using the same function definition from example above
-
-myFun("one", "two", "three")
-
-// a, one
-// b, two
-// manyMoreArgs, [three]
- -

Below, the third argument isn't provided, but manyMoreArgs is still an array (albeit an empty one).

- -
// using the same function definition from example above
-
-myFun("one", "two")
-
-// a, one
-// b, two
-// manyMoreArgs, []
- -

Since theArgs is an array, a count of its elements is given by the length property:

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

In the next example, a rest parameter is used to collect all parameters after the first into an array. Each one of them is then multiplied by the first parameter, and the array is returned:

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

Array methods can be used on rest parameters, but not on the arguments object:

- -
function sortRestArgs(...theArgs) {
-  let sortedArgs = theArgs.sort()
-  return sortedArgs
-}
-
-console.log(sortRestArgs(5, 3, 7, 1)) // 1, 3, 5, 7
-
-function sortArguments() {
-  let sortedArgs = arguments.sort()
-  return sortedArgs  // this will never happen
-}
-
-
-console.log(sortArguments(5, 3, 7, 1))
-// throws a TypeError (arguments.sort is not a function)
-
- -

To use Array methods on the arguments object, it must be converted to a real array first.

- -
function sortArguments() {
-  let args = Array.from(arguments)
-  let sortedArgs = args.sort()
-  return sortedArgs
-}
-console.log(sortArguments(5, 3, 7, 1))  // 1, 3, 5, 7
-
- -

Especificações

- - - - - - - - - - - - -
Especificação
{{SpecName('ESDraft', '#sec-function-definitions', 'Function Definitions')}}
- -

Compatibildiade de navegador

- - - -

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

- -

Consulte também

- - diff --git a/files/pt-pt/web/javascript/reference/global_objects/array/concat/index.html b/files/pt-pt/web/javascript/reference/global_objects/array/concat/index.html deleted file mode 100644 index 237818a04c..0000000000 --- a/files/pt-pt/web/javascript/reference/global_objects/array/concat/index.html +++ /dev/null @@ -1,205 +0,0 @@ ---- -title: Array.prototype.concat() -slug: Web/JavaScript/Reference/Global_Objects/Array/concat -tags: - - JavaScript - - Prototipo - - Referencia - - Vector - - metodo -translation_of: Web/JavaScript/Reference/Global_Objects/Array/concat ---- -
{{JSRef}}
- -

O método concat() é usado para concatenar dois ou mais vectores. Este método não altera os vectores existentes, devolvendo ao invés um novo vector.

- -
var vec1 = ['a', 'b', 'c'];
-var vec2 = ['d', 'e', 'f'];
-
-var vec3 = vec1.concat(vec2);
-
-// vec3 é um novo vector [ "a", "b", "c", "d", "e", "f" ]
- -

Sintaxe

- -
var novo_vector = velho_vector.concat(valor1[, valor2[, ...[, valorN]]])
- -

Parâmetros

- -
-
valorN
-
Vectores e/ou valores a concatenar num novo vector. Veja a descrição detalhada abaixo.
-
- -

Valor devolvido

- -

Uma nova instância de {{jsxref("Array")}}.

- -

Descrição

- -

O método concat cria um novo vector constituído pelos elementos no vector em que foi chamado, seguidos por ordem por, cada argumento, os elementos desse argumento (se o argumento é um vector), ou o argumento em si (se o argumento não é um vector). Não entra recursivamente em vectores inclusos.

- -

O método concat não altera this ou qualquer dos vectores fornecidos como argumentos, devolve sim uma cópia superficial (shallow copy) que contém cópias dos mesmos elementos combinados dos vectores originais. Os elementos dos vectores originais são copiados para o novo vector da seguinte forma:

- - - -
-

Note: Concatenating array(s)/value(s) will leave the originals untouched. Furthermore, any operation on the new array(only if the element is not object reference) will have no effect on the original arrays, and vice versa.

-
- -

Exemplos

- -

Concatenar dois vectores

- -

O código que se segue concatena dois vectores:

- -
var alfa = ['a', 'b', 'c'];
-var numerico = [1, 2, 3];
-
-alfa.concat(numerico);
-// resulta em ['a', 'b', 'c', 1, 2, 3]
-
- -

Concatenar três vectores

- -

O código que se segue concatena três vectores:

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

Concatenar valores para um vector

- -

O código que se segue concatena três valores a um vector:

- -
var alfa = ['a', 'b', 'c'];
-
-var alfaNumerico = alfa.concat(1, [2, 3]);
-
-console.log(alphaNumeric);
-// resulta em ['a', 'b', 'c', 1, 2, 3]
-
- -

Concatenar vectores inclusos

- -

O código que se segue concatena vectores inclusos e demonstra retenção de referências:

- -
var num1 = [[1]];
-var num2 = [2, [3]];
-
-var nums = num1.concat(num2);
-
-console.log(nums);
-// resulta em [[1], 2, [3]]
-
-// modificar o primeiro elemento de num1
-num1[0].push(4);
-
-console.log(nums);
-// resulta em [[1, 4], 2, [3]]
-
- -

Especificações

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName('ES3')}}{{Spec2('ES3')}}Definição inicial. Implementado no JavaScript 1.2.
{{SpecName('ES5.1', '#sec-15.4.4.4', 'Array.prototype.concat')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-array.prototype.concat', 'Array.prototype.concat')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.prototype.concat', 'Array.prototype.concat')}}{{Spec2('ESDraft')}} 
- -

Browser compatibility

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - - - -
CaracterísticaChromeFirefox (Gecko)EdgeInternet ExplorerOperaSafari
Suporte básico{{CompatChrome("1.0")}}{{CompatGeckoDesktop("1.7")}}{{CompatVersionUnknown}}{{CompatIE("5.5")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
CaracterísticaAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

See also

- - diff --git a/files/pt-pt/web/javascript/reference/global_objects/array/find/index.html b/files/pt-pt/web/javascript/reference/global_objects/array/find/index.html deleted file mode 100644 index 3eedeb54a9..0000000000 --- a/files/pt-pt/web/javascript/reference/global_objects/array/find/index.html +++ /dev/null @@ -1,210 +0,0 @@ ---- -title: Array.prototype.find() -slug: Web/JavaScript/Reference/Global_Objects/Array/find -tags: - - Array - - ECMAScript 2015 - - JavaScript - - Method - - polyfill -translation_of: Web/JavaScript/Reference/Global_Objects/Array/find ---- -
{{JSRef}}
- -

O método find() retorna o valor do primeiro elemento do array que satisfaça a função de teste fornecida. Caso contrário o valor {{jsxref("undefined")}} é retornado.

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

Ver também o método {{jsxref("Array.findIndex", "findIndex()")}} , o qual retorna o index de um elemento encontrado num array, em alternativa do seu valor.

- -

É possível obter a posição de um elemento ou verificar a sua existência num array, através da função {{jsxref("Array.prototype.indexOf()")}} ou {{jsxref("Array.prototype.includes()")}}.

- -

Sintaxe

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

Parâmetros

- -
-
callback
-
Função a executar em cada elemento do array, utilizando três argumentos: -
-
element
-
O elemento a ser processado no array.
-
index{{optional_inline}}
-
O index do elemento a ser processado no array.
-
array{{optional_inline}}
-
O array no qual o método find foi chamado.
-
-
-
thisArg {{Optional_inline}}
-
Objeto para usar como this ao executar a callback.
-
- -

Valor de retorno

- -

Um valor do array caso um elemento passe no teste; caso contrário, {{jsxref("undefined")}}.

- -

Descrição

- -

O métodofind executa a callback uma vez para cada index do array até ser encontrado um no qual a callback retorna o valor true. Caso um elemento seja encontrado, o método find retorna imediatamente o seu valor. Caso contrário, o método find retorna {{jsxref("undefined")}}. A função de callback é invocada para cada index do array do 0 ao length - 1 e é invocada para todos os indexes, não apenas nos que tem valor. Isto pode significar que é menos eficiente para o um array com muitos elementos sem valor (sparse array) do que outros métodos que visitam apenas os elementos com valor.

- -

A função de callback é invocada com 3 parâmetros: o valor do elemento, o index do elemento, e o Array no qual é executado.

- -

Se o parâmetro thisArg for disponibilizado ao método find, este será usado como this para cada invocação da callback. Caso contrário, será usado o valor {{jsxref("undefined")}}.

- -

O método find não altera o array no qual é invocado.

- -

A quantidade de elementos processados pelo método find é definida antes da invocação da callback. Os elementos adicionados ao array após o método find ter iniciado não serão visitados pela callback. Se um elemento existente e não visitado, for alterado pela callback, o seu valor que foi passado para a callback será o valor a ser avaliado pelo método find; Os elementos eliminados após o inicio do método find também serão visitados.

- -

Exemplos

- -

Encontrar um objeto num array através de uma das suas propriedades

- -
var inventory = [
-    {name: 'apples', quantity: 2},
-    {name: 'bananas', quantity: 0},
-    {name: 'cherries', quantity: 5}
-];
-
-function isCherries(fruit) {
-    return fruit.name === 'cherries';
-}
-
-console.log(inventory.find(isCherries));
-// { name: 'cherries', quantity: 5 }
- -

Encontrar um número primo num array

- -

O seguinte exemplo encontra um elemento no array que seja um número primo (caso não exista, retorna {{jsxref("undefined")}} ).

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

O seguinte exemplo, apresenta como os elementos não existentes e eliminados são visitados e o seu valor passado para a callback será o seu valor quando visitado.

- -
// Declare array with no element at index 2, 3 and 4
-var a = [0,1,,,,5,6];
-
-// Shows all indexes, not just those that have been assigned values
-a.find(function(value, index) {
-  console.log('Visited index ' + index + ' with value ' + value);
-});
-
-// Shows all indexes, including deleted
-a.find(function(value, index) {
-
-  // Delete element 5 on first iteration
-  if (index == 0) {
-    console.log('Deleting a[5] with value ' + a[5]);
-    delete a[5];
-  }
-  // Element 5 is still visited even though deleted
-  console.log('Visited index ' + index + ' with value ' + value);
-});
-
-
- -

Polyfill

- -

Este método foi adicionado ao ECMAScript 2015 Language Specification e pode não estar disponível em todas as implementações de JavaScript. É possível desenvolver o polyfill do método find com o seguinte código:

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

É melhor não utilizar o polyfill Array.prototype para motores JavaScript obsoletos que não suportem métodos Object.defineProperty, uma vez que, não é possível torna-los não-enumeráveis.

- -

Especificações

- - - - - - - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName('ES2015', '#sec-array.prototype.find', 'Array.prototype.find')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-array.prototype.find', 'Array.prototype.find')}}{{Spec2('ESDraft')}} 
- -

Compatibilidade de Browsers

- -
- - -

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

-
- -

Ver também

- - diff --git a/files/pt-pt/web/javascript/reference/global_objects/array/foreach/index.html b/files/pt-pt/web/javascript/reference/global_objects/array/foreach/index.html deleted file mode 100644 index 77e1bcc9d9..0000000000 --- a/files/pt-pt/web/javascript/reference/global_objects/array/foreach/index.html +++ /dev/null @@ -1,328 +0,0 @@ ---- -title: Array.prototype.forEach() -slug: Web/JavaScript/Reference/Global_Objects/Array/forEach -translation_of: Web/JavaScript/Reference/Global_Objects/Array/forEach ---- -
{{JSRef}}
- -

O método forEach() executa a função que foi fornecida uma vez para cada elemento do vetor (array).

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

Sintaxe

- -
vet.forEach(function callback(presenteValor[, indice[, vetor]]) {
-    //o teu iterador
-}[, argThis]);
- -

Parâmetros

- -
-
callback
-
Função a executar para cada elemento, levando três argumentos: -
-
presenteValor
-
Valor do presente elemento a ser processado do vetor (array).
-
indice{{optional_inline}}
-
Índice do presente elemento a ser processado do vetor (array).
-
vet{{optional_inline}}
-
O vetor (array) a que o forEach() está a ser aplicado.
-
-
-
argThis {{Optional_inline}}
-
-

Valor a usar como this (ou seja o Object de referência) quando é executado o callback.

-
-
- -

Valor devolvido

- -

{{jsxref("undefined")}}.

- -

Descrição

- -

forEach() executa o callback fornecido uma vez para cada elemento presente no vetor (array) por ordem ascendente. Não é invocado para indices de propriedades que foram apagadas ou que não foram inicializadas (ou seja em sparse arrays).

- -

callback é invocado com três argumentos:

- - - -

If a thisArg parameter is provided to forEach(), it will be used as callback's this value.  Otherwise, the value {{jsxref("undefined")}} will be used as its this value. The this value ultimately observable by callback is determined according to the usual rules for determining the this seen by a function.

- -

The range of elements processed by forEach() is set before the first invocation of callback. Elements that are appended to the array after the call to forEach() begins will not be visited by callback. If the values of existing elements of the array are changed, the value passed to callback will be the value at the time forEach() visits them; elements that are deleted before being visited are not visited. If elements that are already visited are removed (e.g. using {{jsxref("Array.prototype.shift()", "shift()")}}) during the iteration, later elements will be skipped - see example below.

- -

forEach() executes the callback function once for each array element; unlike {{jsxref("Array.prototype.map()", "map()")}} or {{jsxref("Array.prototype.reduce()", "reduce()")}} it always returns the value {{jsxref("undefined")}} and is not chainable. The typical use case is to execute side effects at the end of a chain.

- -

forEach() does not mutate the array on which it is called (although callback, if invoked, may do so).

- -
-

There is no way to stop or break a forEach() loop other than by throwing an exception. If you need such behavior, the forEach() method is the wrong tool.

- -

Early termination may be accomplished with:

- - - -

The other Array methods: {{jsxref("Array.prototype.every()", "every()")}}, {{jsxref("Array.prototype.some()", "some()")}}, {{jsxref("Array.prototype.find()", "find()")}}, and {{jsxref("Array.prototype.findIndex()", "findIndex()")}} test the array elements with a predicate returning a truthy value to determine if further iteration is required.

-
- -

Examples

- -

Converting a for loop to forEach

- -

before

- -
const items = ['item1', 'item2', 'item3'];
-const copy = [];
-
-for (let i=0; i<items.length; i++) {
-  copy.push(items[i])
-}
-
- -

after

- -
const items = ['item1', 'item2', 'item3'];
-const copy = [];
-
-items.forEach(function(item){
-  copy.push(item)
-});
-
-
- -

 

- -

Printing the contents of an Array Object

- -

The following code logs a line for each element in an array:

- -
var userInfo = [{
-  name: "Mayank",
-  age: 30
-}, {
-  name: Meha,
-  age: 26
-}];
-
-userInfo.forEach(function(employee) {
-  console.log(employee.name)
-});
-
- -

 

- -

 

- -

 

- -

Printing the contents of an array

- -

The following code logs a line for each element in an array:

- -
function logArrayElements(element, index, array) {
-  console.log('a[' + index + '] = ' + element);
-}
-
-// Notice that index 2 is skipped since there is no item at
-// that position in the array.
-[2, 5, , 9].forEach(logArrayElements);
-// logs:
-// a[0] = 2
-// a[1] = 5
-// a[3] = 9
-
- -

Using thisArg

- -

The following (contrived) example updates an object's properties from each entry in the array:

- -
function Counter() {
-  this.sum = 0;
-  this.count = 0;
-}
-Counter.prototype.add = function(array) {
-  array.forEach(function(entry) {
-    this.sum += entry;
-    ++this.count;
-  }, this);
-  // ^---- Note
-};
-
-const obj = new Counter();
-obj.add([2, 5, 9]);
-obj.count;
-// 3
-obj.sum;
-// 16
-
- -

Since the thisArg parameter (this) is provided to forEach(), it is passed to callback each time it's invoked, for use as its this value.

- -
-

If passing the function argument using an arrow function expression the thisArg parameter can be omitted as arrow functions lexically bind the {{jsxref("Operators/this", "this")}} value.

-
- -

An object copy function

- -

The following code creates a copy of a given object. There are different ways to create a copy of an object; the following is just one way and is presented to explain how Array.prototype.forEach() works by using ECMAScript 5 Object.* meta property functions.

- -
function copy(obj) {
-  const copy = Object.create(Object.getPrototypeOf(obj));
-  const propNames = Object.getOwnPropertyNames(obj);
-
-  propNames.forEach(function(name) {
-    const desc = Object.getOwnPropertyDescriptor(obj, name);
-    Object.defineProperty(copy, name, desc);
-  });
-
-  return copy;
-}
-
-const obj1 = { a: 1, b: 2 };
-const obj2 = copy(obj1); // obj2 looks like obj1 now
-
- -

If the array is modified during iteration, other elements might be skipped.

- -

The following example logs "one", "two", "four". When the entry containing the value "two" is reached, the first entry of the whole array is shifted off, which results in all remaining entries moving up one position. Because element "four" is now at an earlier position in the array, "three" will be skipped. forEach() does not make a copy of the array before iterating.

- -
var words = ['one', 'two', 'three', 'four'];
-words.forEach(function(word) {
-  console.log(word);
-  if (word === 'two') {
-    words.shift();
-  }
-});
-// one
-// two
-// four
-
- -

Polyfill

- -

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

- -
// Production steps of ECMA-262, Edition 5, 15.4.4.18
-// Reference: http://es5.github.io/#x15.4.4.18
-if (!Array.prototype.forEach) {
-
-  Array.prototype.forEach = function(callback/*, thisArg*/) {
-
-    var T, k;
-
-    if (this == null) {
-      throw new TypeError('this is null or not defined');
-    }
-
-    // 1. Let O be the result of calling toObject() passing the
-    // |this| value as the argument.
-    var O = Object(this);
-
-    // 2. Let lenValue be the result of calling the Get() internal
-    // method of O with the argument "length".
-    // 3. Let len be toUint32(lenValue).
-    var len = O.length >>> 0;
-
-    // 4. If isCallable(callback) is false, throw a TypeError exception.
-    // See: http://es5.github.com/#x9.11
-    if (typeof callback !== 'function') {
-      throw new TypeError(callback + ' is not a function');
-    }
-
-    // 5. If thisArg was supplied, let T be thisArg; else let
-    // T be undefined.
-    if (arguments.length > 1) {
-      T = arguments[1];
-    }
-
-    // 6. Let k be 0.
-    k = 0;
-
-    // 7. Repeat while k < len.
-    while (k < len) {
-
-      var kValue;
-
-      // a. Let Pk be ToString(k).
-      //    This is implicit for LHS operands of the in operator.
-      // b. Let kPresent be the result of calling the HasProperty
-      //    internal method of O with argument Pk.
-      //    This step can be combined with c.
-      // c. If kPresent is true, then
-      if (k in O) {
-
-        // i. Let kValue be the result of calling the Get internal
-        // method of O with argument Pk.
-        kValue = O[k];
-
-        // ii. Call the Call internal method of callback with T as
-        // the this value and argument list containing kValue, k, and O.
-        callback.call(T, kValue, k, O);
-      }
-      // d. Increase k by 1.
-      k++;
-    }
-    // 8. return undefined.
-  };
-}
-
- -

Specifications

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

Browser compatibility

- -
- - -

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

-
- -

See also

- - diff --git a/files/pt-pt/web/javascript/reference/global_objects/array/includes/index.html b/files/pt-pt/web/javascript/reference/global_objects/array/includes/index.html deleted file mode 100644 index 201d4c9526..0000000000 --- a/files/pt-pt/web/javascript/reference/global_objects/array/includes/index.html +++ /dev/null @@ -1,175 +0,0 @@ ---- -title: Array.prototype.includes() -slug: Web/JavaScript/Reference/Global_Objects/Array/includes -tags: - - Array - - JavaScript - - Method - - Prototype - - Reference - - polyfill -translation_of: Web/JavaScript/Reference/Global_Objects/Array/includes ---- -
{{JSRef}}
- -

O método includes() determina se um array contém um determinado elemento, devolvendo true ou false. É utilizado o algoritmo sameValueZero para determinar se o elemento especificado foi encontrado.

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

Syntax

- -
arr.includes(searchElement[, fromIndex])
-
- -

Parameters

- -
-
searchElement
-
The element to search for.
-
fromIndex {{optional_inline}}
-
The position in this array at which to begin searching for searchElement. A negative value searches from the index of array.length - fromIndex by asc. Defaults to 0.
-
- -

Return value

- -

A {{jsxref("Boolean")}}.

- -

Examples

- -
[1, 2, 3].includes(2);     // true
-[1, 2, 3].includes(4);     // false
-[1, 2, 3].includes(3, 3);  // false
-[1, 2, 3].includes(3, -1); // true
-[1, 2, NaN].includes(NaN); // true
-
- -

fromIndex is greater than or equal to the array length

- -

If fromIndex is greater than or equal to the length of the array, false is returned. The array will not be searched.

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

Computed index is less than 0

- -

If fromIndex is negative, the computed index is calculated to be used as a position in the array at which to begin searching for searchElement. If the computed index is less than 0, the entire array will be searched.

- -
// array length is 3
-// fromIndex is -100
-// computed index is 3 + (-100) = -97
-
-var arr = ['a', 'b', 'c'];
-
-arr.includes('a', -100); // true
-arr.includes('b', -100); // true
-arr.includes('c', -100); // true
- -

includes() used as a generic method

- -

includes() method is intentionally generic. It does not require this value to be an Array object, so it can be applied to other kinds of objects (e.g. array-like objects). The example below illustrates includes() method called on the function's arguments object.

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

Polyfill

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

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

- -

Specifications

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

Browser compatibility

- -
- - -

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

-
- -

See also

- - diff --git a/files/pt-pt/web/javascript/reference/global_objects/array/index.html b/files/pt-pt/web/javascript/reference/global_objects/array/index.html deleted file mode 100644 index 5f26f41549..0000000000 --- a/files/pt-pt/web/javascript/reference/global_objects/array/index.html +++ /dev/null @@ -1,440 +0,0 @@ ---- -title: Array -slug: Web/JavaScript/Reference/Global_Objects/Array -tags: - - Array - - Class - - Exemplo - - Global Objects - - JavaScript - - Referencia - - 'l10n:priority' -translation_of: Web/JavaScript/Reference/Global_Objects/Array ---- -
{{JSRef}}
- -

A classe de JavaScript Array é um objecto global que é utilizado na construção de matrizes; que são objectos de alto nível, semelhantes a listas.

- -

Descrição

- -

Arrays são objectos em forma de lista, cujo protótipo tem métodos para realizar operações de travessia e mutação. Nem o comprimento de uma array JavaScript nem os tipos dos seus elementos são fixos. Uma vez que o comprimento de uma array pode mudar a qualquer momento, e os dados podem ser armazenados em locais não contíguos da array, não é garantido que uma array JavaScript seja densa; isto depende de como o programador opta por usá-las. Em geral, estas são características convenientes; mas se estas características não forem desejáveis para seu uso particular, você pode considerar o uso de arrays tipadas.

- -

Uma array não pode utilizar strings como índices de elementos (como num {{InterWiki("wikipedia", "Vetor_associativo", "array associativa")}}), deve utilizar números inteiros. A definição ou acesso através de não-inteiros usando notação de parênteses (ou notação de pontos) não definirá ou recuperará um elemento da própria lista da array, mas definirá ou acessará uma variável associada à coleção de propriedades dessa array. As propriedades da array e a lista de elementos do mesmo são separadas, e as operações de translação e mutação da array não podem ser aplicadas a essas propriedades com nome.

- -

Criar uma Array

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

Aceder (através de índice) item da Array

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

Loop over an Array

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

Adicionar um item ao fim da Array

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

Remover um item do fim da Array

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

Remover um item do início da Array

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

Adicionar um item ao início da Array

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

Encontrar o índice dum item na Array

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

Remover um item pela posição do índice

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

Remover items pela posição do índice

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

Copiar uma Array

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

Como aceder a elementos da array

- -

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

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

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

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

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

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

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

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

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

- -
var promise = {
-  'var'  : 'text',
-  'array': [1, 2, 3, 4]
-};
-
-console.log(promise['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

-
- -

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('ESDraft', '#sec-array-objects', 'Array')}}{{Spec2('ESDraft')}}New method added: {{jsxref("Array.prototype.includes()")}}
- -

Compatibilidade de Navegadores

- - - -

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

- -

See also

- - diff --git a/files/pt-pt/web/javascript/reference/global_objects/array/join/index.html b/files/pt-pt/web/javascript/reference/global_objects/array/join/index.html deleted file mode 100644 index aec6f34cc2..0000000000 --- a/files/pt-pt/web/javascript/reference/global_objects/array/join/index.html +++ /dev/null @@ -1,90 +0,0 @@ ---- -title: Array.prototype.join() -slug: Web/JavaScript/Reference/Global_Objects/Array/join -tags: - - JavaScript - - Prototipo - - Referencia - - Vector - - metodo -translation_of: Web/JavaScript/Reference/Global_Objects/Array/join ---- -
{{JSRef}}
- -

O método join() cria e devolve uma string ao concatenar todos os elementos numa array (ou objeto como um vetor / matriz) numa cadeia separada por vírgulas ou outro separador especificado. Se a array tem um só item, esse item é devolvido sem o uso do separador.

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

Sintaxe

- -
vec.join([separador])
- -

Parâmetros

- -
-
separador {{optional_inline}}
-
Especifica uma string (cadeia de caracteres) para separar cada elemento do vetor. O separador é convertido em cadeia se for necessário. Se for omitido, os elementos serão separados por virgulas (","). Se separador é uma cadeia vazia, todos os elementos são unidos sem qualquer caráter entre eles.
-
- -

Resultado

- -

Uma cadeia (de caracteres) com todos os elementos do vetor unidos. Se vec.length é 0, é devolvida uma cadeia vazia.

- -

Descrição

- -

As conversões de todos os elementos do vetor para cadeias (de caracteres) são unidas numa única cadeia.

- -

Caso algum elemento seja undefined, null ou um vetor vazio [], este será convertido numa cadeia vazia.

- -

Exemplos

- -

Juntar um vetor de quatro formas diferentes

- -

O exemplo que se segue cria um vetor, a, com três elementos, depois disso une o vetor quatro vezes: usando o separador predefinido, uma vírgula e um espaço, o símbolo mais, e finalmente uma cadeia (de caracteres) vazia.

- -
var a = ['Vento', 'Chuva', 'Fogo'];
-a.join();      // 'Vento,Chuva,Fogo'
-a.join(', ');  // 'Vento, Chuva, Fogo'
-a.join(' + '); // 'Vento + Chuva + Fogo'
-a.join('');    // 'VentoChuvaFogo'
- -

Juntar um objeto como vetor

- -

O seguinte exemplo junta um objeto como vetor (arguments), ao chamar {{jsxref("Function.prototype.call")}} no Array.prototype.join.

- -
function f(a, b, c) {
-  var s = Array.prototype.join.call(arguments);
-  console.log(s); // '1,a,true'
-}
-f(1, 'a', true);
-// valor devolvido: "1,a,true"
-
- -

Especificações

- - - - - - - - - - -
Especificação
{{SpecName('ESDraft', '#sec-array.prototype.join', 'Array.prototype.join')}}
- -

Compatibilidade

- - - -

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

- -

Veja também

- - diff --git a/files/pt-pt/web/javascript/reference/global_objects/array/map/index.html b/files/pt-pt/web/javascript/reference/global_objects/array/map/index.html deleted file mode 100644 index 12910ebc2a..0000000000 --- a/files/pt-pt/web/javascript/reference/global_objects/array/map/index.html +++ /dev/null @@ -1,366 +0,0 @@ ---- -title: Array.prototype.map() -slug: Web/JavaScript/Reference/Global_Objects/Array/map -tags: - - Array - - ECMAScript 5 - - JavaScript - - Prototype - - Referencia - - metodo - - polyfill -translation_of: Web/JavaScript/Reference/Global_Objects/Array/map ---- -
{{JSRef}}
- -

O método map() cria uma nova array preenchida com os resultados da chamada de uma função fornecida em cada elemento da matriz de chamada.

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

Sintaxe

- -
let new_array = arr.map(function callback( currentValue[, index[, array]]) {
-    // retorna novo elemento para new_array
-}[, thisArg])
-
- -

Parameteros

- -
-
callback
-
-

Função que é chamada para cada elemento de arr. Cada vez que a função callback é executada, o valor devolvido é acrescentado a new_array.

- -

A função callback aceita os seguintes argumentos:

- -
-
currentValue
-
O elemento da matriz a ser processado.
-
index{{optional_inline}}
-
O indice do elemento da matriz a ser processado.
-
array{{optional_inline}}
-
A matriz em que a função map foi chamada.
-
-
-
thisArg{{optional_inline}}
-
Valor para usar como this ao executar a função callback.
-
- -

Valor de retorno

- -

Uma nova matriz em que cada elemento é um resultado da função callback..

- -

Descrição

- -

map chama a função callback uma vez por cada elemento na matriz, por ordem, e cria uma matriz com os resultados. callback é só chamada nos indices da matriz que têm valores (inclusive {{jsxref("undefined")}}).

- -

Não é chamada para elementos que não pertecem à matriz; isto sendo:

- - - -

Quando não usar map()

- -

Como map map cira uma nova matriz, é um anti-pattern usar a função quando não se vai usar o valor devolvido; use antes {{jsxref("Array/forEach", "forEach")}} ou {{jsxref("for...of", "for-of")}}.

- -

Não deve usar map se:

- - - -

Parameteros em detalhe

- -

callback é chamada com três argumentos: o valor do elemento, o indice do elemento, e a matriz do objeto a ser mapeado.

- -

Se o parametero thisArg é fornecido, é usado como o valor de this na função callback. Se não, o valor {{jsxref("undefined")}} é usado como o valor de this. O valor de this no corpo da função callback é determinado de acordo com as regras habituais para determinar o valor de this numa função.

- -

map não modifica a matriz em que é chamada (embora a função callback, se invocada, possa fazê-lo).

- -

A série de elementos processados por map é definida antes da primeira invocação de callback. Os elementos que são anexados ao conjunto após a chamada para map não serão visitados por callback. Se os elementos existentes da matriz forem alterados, o seu valor como passado para callback será o valor no momento em que map os visitar. Os elementos que são apagados após a chamada para map começa e antes de serem visitados, não são visitados.

- -

Devido ao algoritmo defenido na especificação, se a matriz em que map é chamada for esparsa, a matriz resultante também o será com os mesmos indices em branco.

- -

Polyfill

- -

map was added to the ECMA-262 standard in the 5th edition. Therefore, it may not be present in all implementations of the standard.

- -

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

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

Examples

- -

Mapping an array of numbers to an array of square roots

- -

The following code takes an array of numbers and creates a new array containing the square roots of the numbers in the first array.

- -
let numbers = [1, 4, 9]
-let roots = numbers.map(function(num) {
-    return Math.sqrt(num)
-})
-// roots is now     [1, 2, 3]
-// numbers is still [1, 4, 9]
-
- -

Using map to reformat objects in an array

- -

The following code takes an array of objects and creates a new array containing the newly reformatted objects.

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

Mapping an array of numbers using a function containing an argument

- -

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

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

Using map generically

- -

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

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

Using map generically querySelectorAll

- -

This example shows how to iterate through a collection of objects collected by querySelectorAll. This is because querySelectorAll returns a NodeList (which is a collection of objects).

- -

In this case, we return all the selected options' values on the screen:

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

An easier way would be the {{jsxref("Array.from()")}} method.

- -

Tricky use case

- -

(inspired by this blog post)

- -

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

- -

Consider:

- -
["1", "2", "3"].map(parseInt)
- -

While one might expect [1, 2, 3], the actual result is [1, NaN, NaN].

- -

{{jsxref("parseInt")}} is often used with one argument, but takes two. The first is an expression and the second is the radix to the callback function, Array.prototype.map passes 3 arguments:

- - - -

The third argument is ignored by {{jsxref("parseInt")}}—but not the second one! This is the source of possible confusion.

- -

Here is a concise example of the iteration steps:

- -
// parseInt(string, radix) -> map(parseInt(value, index))
-/*  first iteration  (index is 0): */ parseInt("1", 0)  // 1
-/*  second iteration (index is 1): */ parseInt("2", 1)  // NaN
-/*  third iteration  (index is 2): */ parseInt("3", 2)  // NaN
-
- -

Then let's talk about solutions.

- -
function returnInt(element) {
-  return parseInt(element, 10)
-}
-
-['1', '2', '3'].map(returnInt); // [1, 2, 3]
-// Actual result is an array of numbers (as expected)
-
-// Same as above, but using the concise arrow function syntax
-['1', '2', '3'].map( str => parseInt(str) )
-
-// A simpler way to achieve the above, while avoiding the "gotcha":
-['1', '2', '3'].map(Number)  // [1, 2, 3]
-
-// But unlike parseInt(), Number() will also return a float or (resolved) exponential notation:
-['1.1', '2.2e2', '3e300'].map(Number)  // [1.1, 220, 3e+300]
-
-// For comparison, if we use parseInt() on the array above:
-['1.1', '2.2e2', '3e300'].map( str => parseInt(str) ) // [1, 2, 3]
-
- -

One alternative output of the map method being called with {{jsxref("parseInt")}} as a parameter runs as follows:

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

Mapped array contains undefined

- -

When {{jsxref("undefined")}} or nothing is returned:

- -
let numbers = [1, 2, 3, 4]
-let filteredNumbers = numbers.map(function(num, index) {
-  if (index < 3) {
-     return num
-  }
-})
-// index goes from 0, so the filterNumbers are 1,2,3 and undefined.
-// filteredNumbers is [1, 2, 3, undefined]
-// numbers is still [1, 2, 3, 4]
-
-
- -

Especificações

- - - - - - - - - - - - -
Especificação
{{SpecName('ESDraft', '#sec-array.prototype.map', 'Array.prototype.map')}}
- -

Compatibilidade

- -
- - -

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

-
- -

Ver também

- - diff --git a/files/pt-pt/web/javascript/reference/global_objects/array/pop/index.html b/files/pt-pt/web/javascript/reference/global_objects/array/pop/index.html deleted file mode 100644 index 440ea3e6ee..0000000000 --- a/files/pt-pt/web/javascript/reference/global_objects/array/pop/index.html +++ /dev/null @@ -1,96 +0,0 @@ ---- -title: Array.prototype.pop() -slug: Web/JavaScript/Reference/Global_Objects/Array/pop -tags: - - JavaScript - - Lista - - Prototipo - - Referencia - - metodo -translation_of: Web/JavaScript/Reference/Global_Objects/Array/pop ---- -
{{JSRef}}
- -

O método pop() remove o último elemento de um array e retorna esse elemento. Este método altera o tamanho do array.

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

Syntax

- -
arr.pop()
- -

Valor retornado

- -

O elemento removido do array; {{jsxref("undefined")}} se o array estiver vazio.

- -

Descrição

- -

O método pop remove o último elemento de um array e retorna esse elemento para a função que o chamou.

- -

pop é um método intencionalmente genérico; este método pode ser {{jsxref("Function.call", "called", "", 1)}} ou {{jsxref("Function.apply", "applied", "", 1)}} para objectos parecidos com arrays. Objectos que não contenham a propriedade length (tamanho) que reflete o último elemento numa lista de consecutivas propriedades numéricas zero-based, pode não se comportar de maneira significativa.

- -

Se o método pop() for chamado num array vazio este retorna {{jsxref("undefined")}}.

- -

Exemplos

- -

Remover o último elemento de um array

- -

O seguinte exemplo cria um array peixes que contêm quatro elementos, e depois remove o último elemento.

- -
var peixes = ['anjo', 'palhaço', 'mandarim', 'esturjão'];
-
-var popped = peixes.pop();
-
-console.log(peixes); // ['anjo', 'palhaço', 'mandarim']
-
-console.log(popped); // 'esturjão'
- -

Especificações

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Definição inicial. Implementada no JavaScript 1.2.
{{SpecName('ES5.1', '#sec-15.4.4.6', 'Array.prototype.pop')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-array.prototype.pop', 'Array.prototype.pop')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.prototype.pop', 'Array.prototype.pop')}}{{Spec2('ESDraft')}} 
- -

Compatibilidade

- -
- - -

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

-
- -

Ver também 

- - diff --git a/files/pt-pt/web/javascript/reference/global_objects/array/reverse/index.html b/files/pt-pt/web/javascript/reference/global_objects/array/reverse/index.html deleted file mode 100644 index a442018c61..0000000000 --- a/files/pt-pt/web/javascript/reference/global_objects/array/reverse/index.html +++ /dev/null @@ -1,133 +0,0 @@ ---- -title: Array.prototype.reverse() -slug: Web/JavaScript/Reference/Global_Objects/Array/reverse -translation_of: Web/JavaScript/Reference/Global_Objects/Array/reverse ---- -
{{JSRef}}
- -

O método reverse() inverte um vector (Array). O primeiro elemento torna-se o último, e o último elemento torna-se o primeiro.

- -
var a = ['um', 'dois', 'três'];
-a.reverse();
-
-console.log(a); // ['três', 'dois', 'um']
-
- -

Sintaxe

- -
a.reverse()
- -

Valor devolvido

- -

O vector (Array) invertido.

- -

Descrição

- -

O método reverse transpõe os elementos do vector que o chamou, mudando o vector, e devolvendo uma referência para o vector.

- -

Exemplos

- -

Invertendo os elementos num vector

- -

O exemplo que se segue cria um vector a, que contém três elementos, e depois o inverte. A chamada a reverse() devolve uma referência para o vector invertido a.

- -
var a = ['um', 'dois', 'três'];
-var invertido = a.reverse();
-
-console.log(a);        // ['três', 'dois', 'um']
-console.log(invertido); // ['três', 'dois', 'um']
-
- -

Especificações

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.4.4.8', 'Array.prototype.reverse')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-array.prototype.reverse', 'Array.prototype.reverse')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.prototype.reverse', 'Array.prototype.reverse')}}{{Spec2('ESDraft')}} 
- -

Browser compatibility

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

See also

- - diff --git a/files/pt-pt/web/javascript/reference/global_objects/array/slice/index.html b/files/pt-pt/web/javascript/reference/global_objects/array/slice/index.html deleted file mode 100644 index 48820a1ff7..0000000000 --- a/files/pt-pt/web/javascript/reference/global_objects/array/slice/index.html +++ /dev/null @@ -1,154 +0,0 @@ ---- -title: Array.prototype.slice() -slug: Web/JavaScript/Reference/Global_Objects/Array/slice -tags: - - Array - - JavaScript - - Prototipo - - Referencia - - metodo -translation_of: Web/JavaScript/Reference/Global_Objects/Array/slice ---- -
{{JSRef}}
- -

O método slice() devolve uma cópia rasa (é feita uma cópia dos pointers se for um objeto) de uma parte de uma matriz num novo objeto de array selecionado do start (início incluído) ao end (fim excluído) onde o start e o end representam o índice de itens dessa matriz. A matriz original não é modificada.

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

Sintaxe

- -
arr.slice([start[, end]])
-
- -

Parâmetros

- -
-
start {{optional_inline}}
-
Indice de base zero, onde coméça a cópia.
-
Um índice negativo pode ser utilizado, indicando um intervalo a partir do fim da sequência. slice(-2) extrai os dois últimos elementos da sequência.
-
Se start é undefined, slice coméça a partir do indice 0.
-
Se start é maior que o último índice da sequência, uma matriz vazia é devolvida.
-
end {{optional_inline}}
-
Índice antes do qual se deve terminar a extração. slice extrai até o valor de indice end, mas sem incluir end. Por exemplo, slice(1,4) extrai do segundo até ao quarto elemento (elementos indexados 1, 2, e 3).
-
Pode ser utilizado um índice negativo, indicando o último índice a partir do fim da sequência. slice(2,-1) extrai do terceiro até ao penúltimo elemento na sequência.
-
Se end é omisso, slice extrai todos os elementos até ao fim da sequência (arr.length).
-
Se end é maior que o comprimento da sequência, slice extrai todos os elementos até ao fim da sequência (arr.length).
-
- -

Resultado

- -

Uma matriz nova contendo os elementos extraídos.

- -

Descrição

- -

slice não altera a matriz original. Devolve uma cópia rasa dos elementos da matriz original. Os elementos da matriz original são copiados para a matriz devolvida como se segue:

- - - -

Se um novo elemento é adicionado a qualquer das matrizes, a outra matriz não é afetada.

- -

Exemplos

- -

Devolver uma porção duma matriz

- -
let fruits = ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango']
-let citrus = fruits.slice(1, 3)
-
-// fruits contêm ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango']
-// citrus contêm ['Orange','Lemon']
-
- -

Usar slice

- -

No seguinte exemplo, slice cria uma array (matriz), newCar, a partir de myCar. Ambos incluem uma referência ao objeto myHonda. Quando a propriedade color (cor) de myHonda é mudada para purple (roxo), ambas matrizes refletem a alteração.

- -
// Usando slice, cria newCar a partir de myCar.
-let myHonda = { color: 'red', wheels: 4, engine: { cylinders: 4, size: 2.2 } }
-let myCar = [myHonda, 2, 'cherry condition', 'purchased 1997']
-let newCar = myCar.slice(0, 2)
-
-// Imprime os valors de myCar, newCar, a propriadade
-// color de myHonda em ambas arrays.
-console.log('myCar = ' + JSON.stringify(myCar))
-console.log('newCar = ' + JSON.stringify(newCar))
-console.log('myCar[0].color = ' + myCar[0].color)
-console.log('newCar[0].color = ' + newCar[0].color)
-
-// Mude a propriadade color de myHonda.
-myHonda.color = 'purple'
-console.log('A nova cor de my Honda é ' + myHonda.color)
-
-// Imprime a propriadade color de myHonda em ambas arrays.
-console.log('myCar[0].color = ' + myCar[0].color)
-console.log('newCar[0].color = ' + newCar[0].color)
-
- -

Este script imprime:

- -
myCar = [{color: 'red', wheels: 4, engine: {cylinders: 4, size: 2.2}}, 2,
-         'cherry condition', 'purchased 1997']
-newCar = [{color: 'red', wheels: 4, engine: {cylinders: 4, size: 2.2}}, 2]
-myCar[0].color = red
-newCar[0].color = red
-A nova cor de my Honda é purple
-myCar[0].color = purple
-newCar[0].color = purple
-
- -

Objetos parecidos com Array

- -

O método slice tembém pode ser chamado para converter objetos / coleções do estilo matriz para um objeto Array. É só preciso {{jsxref("Function.prototype.bind", "bind")}} o método ao objeto. Os {{jsxref("Functions/arguments", "argumentos")}} dentro da função são um exemplo de um "objeto de estilo matriz".

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

Binding pode ser feito com o método {{jsxref("Function.prototype.call", "call()")}} de {{jsxref("Function.prototype")}} e também pode ser simplificado a usar  [].slice.call(arguments) invés de Array.prototype.slice.call.

- -

Pode ser simplificado a usar {{jsxref("Function.prototype.bind", "bind")}}.

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

Especificações

- - - - - - - - - - - - -
Especificação
{{SpecName('ESDraft', '#sec-array.prototype.slice', 'Array.prototype.slice')}}
- -

Compatibilidade

- - - -

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

- -

Veja também

- - diff --git a/files/pt-pt/web/javascript/reference/global_objects/arraybuffer/index.html b/files/pt-pt/web/javascript/reference/global_objects/arraybuffer/index.html deleted file mode 100644 index c612f44b26..0000000000 --- a/files/pt-pt/web/javascript/reference/global_objects/arraybuffer/index.html +++ /dev/null @@ -1,219 +0,0 @@ ---- -title: ArrayBuffer -slug: Web/JavaScript/Reference/Global_Objects/ArrayBuffer -translation_of: Web/JavaScript/Reference/Global_Objects/ArrayBuffer ---- -
{{JSRef}}
- -
ArrayBuffer é um objeto utilizado para representar um buffer de dados em binário de tamanho pré-definido. Não é possivel manipular o conteudo do buffer diretamente; em vez disso, tem de se criar um dos typed array objects ou um objeto {{jsxref("DataView")}} que representa um buffer num formato especifico, e usa-o para ler e escrever  o conteudo do buffer. 
- -
 
- -

Sintaxe

- -
new ArrayBuffer(length)
-
- -

Parametros

- -
-
length
-
O tamanho, em bytes, do array buffer que se pretende criar.
-
- -

Retorno

- -

 Um novo objecto do tipo ArrayBuffer do tamanho especificado. O respetivo conteudo é inicializado a 0.

- -

Excepções

- -

A {{jsxref("RangeError")}} é lançada caso o tamanho (length) é maior do que {{jsxref("Number.MAX_SAFE_INTEGER")}} (>= 2 ** 53) ou caso seja negativo.

- -

Descrição

- -

O construtor de ArrayBuffer cria um novo objeto do tipo ArrayBuffer com o tamanho especificado em bytes.

- -

Obter um array buffer a partir de dados existentes

- - - -

Propriedades

- -
-
ArrayBuffer.length
-
Propriedade length do construtor de  ArrayBuffer cujo valor é 1.
-
{{jsxref("ArrayBuffer.@@species", "get ArrayBuffer[@@species]")}}
-
A função do contrutor que é usado para criar objetos derivados.
-
{{jsxref("ArrayBuffer.prototype")}}
-
Permite adicionar novas propriedades a todos os objetos do tipo ArrayBuffer.
-
- -

Métodos

- -
-
{{jsxref("ArrayBuffer.isView", "ArrayBuffer.isView(arg)")}}
-
Devolve true caso arg é  um tipo de representação do ArrayBuffer, como typed array objects ou {{jsxref("DataView")}}. Devolve false caso contrário
-
{{jsxref("ArrayBuffer.transfer", "ArrayBuffer.transfer(oldBuffer [, newByteLength])")}} {{experimental_inline}}
-
Devolve um novo objeto ArrayBuffer cujo conteúdo é obtido do oldBuffer e ou é truncado ou preenchido a zeros pelo  newByteLength.
-
- -

Instâncias ArrayBuffer

- -

Todas as instâncias de ArrayBuffer herdam de {{jsxref("ArrayBuffer.prototype")}}.

- -

Propriedades

- -

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

- -

Métodos

- -

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

- -
-
{{jsxref("ArrayBuffer.slice()")}} {{non-standard_inline}}
-
Tem a mesma funcionalidade que {{jsxref("ArrayBuffer.prototype.slice()")}}.
-
- -

Exemplo

- -

Neste exemplo, criamos um buffer de 8 bytes com representação {{jsxref("Global_Objects/Int32Array", "Int32Array")}} a referênciar o buffer:

- -
var buffer = new ArrayBuffer(8);
-var view   = new Int32Array(buffer);
- -

Especificação

- - - - - - - - - - - - - - - - - - - - - - - - -
EspecificaçãoStatusComentário
{{SpecName('Typed Array')}}{{Spec2('Typed Array')}}Substituido por ECMAScript 6.
{{SpecName('ES6', '#sec-arraybuffer-constructor', 'ArrayBuffer')}}{{Spec2('ES6')}} -

Definição inicial no stardard da ECMA. Especificar que new era necessário.

-
{{SpecName('ESDraft', '#sec-arraybuffer-constructor', 'ArrayBuffer')}}{{Spec2('ESDraft')}} 
- -

Compatibilidade nos navegadores

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support7.0{{CompatGeckoDesktop("2")}}1011.65.1
ArrayBuffer() without new throws{{CompatUnknown}}{{CompatGeckoDesktop("44")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
ArrayBuffer.slice() {{non-standard_inline}}{{CompatNo}}{{CompatVersionUnknown}}
- {{CompatNo}} {{CompatGeckoDesktop("53")}}
{{CompatNo}}{{CompatNo}}{{CompatUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support4.0{{CompatVersionUnknown}}{{CompatGeckoMobile("2")}}1011.64.2
ArrayBuffer() without new throws{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("44")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
ArrayBuffer.slice() {{non-standard_inline}}{{CompatNo}}{{CompatNo}}{{CompatVersionUnknown}}
- {{CompatNo}} {{CompatGeckoMobile("53")}}
{{CompatNo}}{{CompatNo}}{{CompatUnknown}}
-
- -

Notas de compatibilidade

- -

Com ECMAScript 2015, construtores de ArrayBuffer são obrigados a usar o operador {{jsxref("Operators/new", "new")}}. Daqui adiante ao invocar ArrayBuffer como uma função sem new irá lançar uma exceção {{jsxref("TypeError")}}.

- -
var dv = ArrayBuffer(10);
-// TypeError: calling a builtin ArrayBuffer constructor
-// without new is forbidden
- -
var dv = new ArrayBuffer(10);
- -

Ver também

- - diff --git a/files/pt-pt/web/javascript/reference/global_objects/asyncfunction/index.html b/files/pt-pt/web/javascript/reference/global_objects/asyncfunction/index.html deleted file mode 100644 index 4e454bacd9..0000000000 --- a/files/pt-pt/web/javascript/reference/global_objects/asyncfunction/index.html +++ /dev/null @@ -1,124 +0,0 @@ ---- -title: AsyncFunction -slug: Web/JavaScript/Reference/Global_Objects/AsyncFunction -translation_of: Web/JavaScript/Reference/Global_Objects/AsyncFunction ---- -
{{JSRef}}
- -
O constructor da função Async cria um novo objecto {{jsxref("Statements/async_function", "async function")}}. Em Javascript todas as funções asíncronas são na verdade objectos AsyncFunction.
- -

 

- -

Note-se que AsyncFunction não é um objecto global. Pode ser obtido da seguinte forma.

- -
Object.getPrototypeOf(async function(){}).constructor
-
- -

Síntaxe

- -
new AsyncFunction([arg1[, arg2[, ...argN]],] functionBody)
- -

Parâmetros

- -
-
arg1, arg2, ... argN
-
Nomes usados pela função como nomes formais de argumentos . Cada um dos argumentos tem que ser uma string que corresponde a um identificador válido JavaScript ou uma lista separada por vírgulas; por exemplo "x", "theValue", ou "a,b".
-
functionBody
-
Uma string com os termos JavaScript que fazem parte da definição da função.
-
- -

Descrição

- -

Os objectos {{jsxref("Statements/async_function", "async function")}} criados com o constructor AsyncFunction passam por um parsing quando as funções são criadas. Isto é menos eficiente que declarar uma função asíncrona com {{jsxref("Statements/async_function", "async function expression")}} e chamá-la no código porque dessa forma a função passa pelo parsing ao mesmo tempo que o resto do código.

- -

Todos os argumentos passados à função são tratados como os nomes dos identificadores dos parâmetros na função a ser criada, na ordem que são declarados.

- -
-

Nota: {{jsxref("Statements/async_function", "async functions")}} criado com o constructor AsyncFunction não estão encapsulados ao contexto da sua criação, são sempre criados no âmbito global.

- -

Ao correr, podem aceder às suas prórpias variáveis e às variáveis globais, no entanto não conseguem aceder às que estão no contexto donde o constructor AsyncFunction foi chamado. Isto é diferente de chamar {{jsxref("Global_Objects/eval", "eval")}} com código para uma função asíncrona.

-
- -

A invocação do constructor AsyncFunction como uma função, i.e. sem usar o operador new tem o mesmo efeito que invocá-lo como constructor.

- -

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

- -

Propriedades

- -
-
AsyncFunction.length
-
A propriedade comprimento do constructor do AsyncFunction, cujo valor é 1.
-
{{jsxref("AsyncFunction.prototype")}}
-
Permite adicionar propriedades a todos os objectos que são funções asíncronas.
-
- -

AsyncFunction prototype object

- -

Propriedades

- -
{{page('/pt-PT/docs/Web/JavaScript/Reference/Global_Objects/AsyncFunction/prototype', 'Properties')}}
- -

Instâncias de AsyncFunction

- -

As instâncias de AsyncFunction herdam métodos e propriedades do {{jsxref("AsyncFunction.prototype")}}. Tal como com qualquer constructor pode-se mudar o prototype object para aplicar mudanças a todos as instâncias de AsyncFunction.

- -

Exemplos

- -

Exemplo de criação de uma função async a partir de um constructor AsyncFunction

- -
function resolveAfter2Seconds(x) {
-  return new Promise(resolve => {
-    setTimeout(() => {
-      resolve(x);
-    }, 2000);
-  });
-}
-
-var AsyncFunction = Object.getPrototypeOf(async function(){}).constructor
-
-var a = new AsyncFunction('a',
-                          'b',
-                          'return await resolveAfter2Seconds(a) + await resolveAfter2Seconds(b);');
-
-a(10, 20).then(v => {
-  console.log(v); // prints 30 after 4 seconds
-});
-
- -

Especificações

- - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-async-function-objects', 'AsyncFunction object')}}{{Spec2('ESDraft')}}Definição inicial em ES2017.
- -

Compatibilidade de navegadores

- -
- - -

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

-
- -

See also

- - diff --git a/files/pt-pt/web/javascript/reference/global_objects/boolean/index.html b/files/pt-pt/web/javascript/reference/global_objects/boolean/index.html deleted file mode 100644 index e8482a2c0e..0000000000 --- a/files/pt-pt/web/javascript/reference/global_objects/boolean/index.html +++ /dev/null @@ -1,156 +0,0 @@ ---- -title: Booliano -slug: Web/JavaScript/Reference/Global_Objects/Boolean -tags: - - Boolean - - Booliano - - Constructor - - JavaScript -translation_of: Web/JavaScript/Reference/Global_Objects/Boolean ---- -
{{JSRef}}
- -

O objeto Boolean é um wrapper objeto para um valor booliano.

- -

Sintaxe

- -
new Boolean([value])
- -

Parâmetros

- -
-
value
-
Opcional. O valor incial do objeto Boolean.
-
- -

Descrição

- -

The value passed as the first parameter is converted to a boolean value, if necessary. If the value is omitted or is 0, -0, {{jsxref("null")}}, false, {{jsxref("NaN")}}, {{jsxref("undefined")}}, or the empty string (""), the object has an initial value of false. If the DOM object {{domxref("document.all")}} is passed as a parameter, the new boolean object also has an initial value of false. All other values, including any object or the string "false", create an object with an initial value of true.

- -

Do not confuse the primitive Boolean values true and false with the true and false values of the Boolean object.

- -

Any object of which the value is not {{jsxref("undefined")}} or {{jsxref("null")}}, including a Boolean object whose value is false, evaluates to true when passed to a conditional statement. For example, the condition in the following {{jsxref("Statements/if...else", "if")}} statement evaluates to true:

- -
var x = new Boolean(false);
-if (x) {
-  // this code is executed
-}
-
- -

This behavior does not apply to Boolean primitives. For example, the condition in the following {{jsxref("Statements/if...else", "if")}} statement evaluates to false:

- -
var x = false;
-if (x) {
-  // this code is not executed
-}
-
- -

Do not use a Boolean object to convert a non-boolean value to a boolean value. Instead, use Boolean as a function to perform this task:

- -
var x = Boolean(expression);     // preferred
-var x = new Boolean(expression); // don't use
-
- -

If you specify any object, including a Boolean object whose value is false, as the initial value of a Boolean object, the new Boolean object has a value of true.

- -
var myFalse = Boolean(false);   // initial value of false
-var g = Boolean(myFalse);       // initial value of true
-var myString = new String('Hello'); // string object
-var s = Boolean(myString);      // initial value of true
-
- -

Do not use a Boolean object in place of a Boolean primitive.

- -

Propriedades

- -
-
Boolean.length
-
Length property whose value is 1.
-
{{jsxref("Boolean.prototype")}}
-
Represents the prototype for the Boolean constructor.
-
- -

Métodos

- -

While the global Boolean object contains no methods of its own, it does inherit some methods through the prototype chain:

- -

Instâncias Boolean

- -

All Boolean instances inherit from {{jsxref("Boolean.prototype")}}. As with all constructors, the prototype object dictates instances' inherited properties and methods.

- -

Propridades

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

Métodos

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

Exemplos

- -

Criar objetos Boolean com um valor inicial de false

- -
var bNoParam = Boolean();
-var bZero = Boolean(0);
-var bNull = Boolean(null);
-var bEmptyString = Boolean('');
-var bfalse = Boolean(false);
-
- -

Criar objetos Boolean com um valor inicial de verdadeiro

- -
var btrue = Boolean(true);
-var btrueString = Boolean('true');
-var bfalseString = Boolean('false');
-var bSuLin = Boolean('Su Lin');
-var bArrayProto = Boolean([]);
-var bObjProto = Boolean({});
-
- -

Especificações

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.6', 'Boolean')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-boolean-objects', 'Boolean')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-boolean-objects', 'Boolean')}}{{Spec2('ESDraft')}} 
- -

Compatibilidade de navegador

- -
- - -

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

-
- -

Consulte também

- - diff --git a/files/pt-pt/web/javascript/reference/global_objects/encodeuri/index.html b/files/pt-pt/web/javascript/reference/global_objects/encodeuri/index.html deleted file mode 100644 index 5f8c84ca8e..0000000000 --- a/files/pt-pt/web/javascript/reference/global_objects/encodeuri/index.html +++ /dev/null @@ -1,152 +0,0 @@ ---- -title: encodeURI() -slug: Web/JavaScript/Reference/Global_Objects/encodeURI -translation_of: Web/JavaScript/Reference/Global_Objects/encodeURI ---- -
{{jsSidebar("Objects")}}
- -

O método encodeURI() codifica um Uniform Resource Identifier (URI) substituindo cada instancia de determinados caracteres por um, dois, três, ou quatro sequências de escape que representem a codificação UTF-8 do caracter (apenas serão quatro sequências de caracteres de escape para caracteres compostos por dois caracteres de "substituição").

- -

Sintaxe

- -
encodeURI(URI)
- -

Parâmetros

- -
-
URI
-
Um Uniform Resource Identifier completo.
-
- -

Descrição

- -

Assumindo que o URI é um URI completo, não serão codificados caracteres reservados que tenham significado especial no URI.

- -

encodeURI substitui todos os caracteres excepto as seguintes sequências de escape UTF-8:

- - - - - - - - - - - - - - - - - - - - -
TipoIncluído
Caracteres reservados; , / ? : @ & = + $
Caracteres excluídosalfabéticos, dígitos decimais , - _ . ! ~ * ' ( )
Ponto#
- -

Note-se que o método encodeURI não consegue criar correctamente os pedidos HTTP GET e POST, o mesmo aplica-se para XMLHTTPRequests, porque os caracteres "&", "+", e "=" não são codificados, por se tratarem de caracteres especiais nos pedidos GET e POST. {{jsxref("encodeURIComponent")}}, no entanto, codifica estes caracteres.

- -

Note-se que será lançado um {{jsxref("URIError")}} caso se tente codificar um substituto que não faça parte de um par superior-inferior, p.ex.,

- -
// par superior-inferior ok
-console.log(encodeURI('\uD800\uDFFF'));
-
-// substituição única de par superior lança "URIError: malformed URI sequence"
-console.log(encodeURI('\uD800'));
-
-// substituição única de par inferior lança "URIError: malformed URI sequence"
-console.log(encodeURI('\uDFFF')); 
- -

Note-se também que caso se pretenda seguir a mais recente norma para URLs RFC3986, que torna os parênteses rectos reservados (para IPv6) e, por consequência, não será codificado quando fizer parte de um URL (como um host), o seguinte exemplo de código pode ajudar:

- -
function fixedEncodeURI (str) {
-    return encodeURI(str).replace(/%5B/g, '[').replace(/%5D/g, ']');
-}
- -

Especificações

- - - - - - - - - - - - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition.
{{SpecName('ES5.1', '#sec-15.1.3.3', 'encodeURI')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-encodeuri-uri', 'encodeURI')}}{{Spec2('ES6')}} 
- -

Compatibilidade com navegador

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - -
FuncionalidadeChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FuncionalidadeAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Veja também

- - diff --git a/files/pt-pt/web/javascript/reference/global_objects/function/arguments/index.html b/files/pt-pt/web/javascript/reference/global_objects/function/arguments/index.html deleted file mode 100644 index 4c9bf9e96e..0000000000 --- a/files/pt-pt/web/javascript/reference/global_objects/function/arguments/index.html +++ /dev/null @@ -1,88 +0,0 @@ ---- -title: Function.arguments -slug: Web/JavaScript/Reference/Global_Objects/Function/arguments -translation_of: Web/JavaScript/Reference/Global_Objects/Function/arguments ---- -
{{JSRef}} {{deprecated_header}}
- -
A propriedade function.arguments refere-se a um objecto com aspecto de array que corresponde aos argumentos da função. Ao invés disso, use a variável {{jsxref("Functions/arguments", "arguments")}}. Esta propriedade é proibida no modo strict devido ao tail call optimization.
- -

Descrição

- -

A síntaxe function.arguments está obsoleta. A forma recomendade de aceder ao objecto {{jsxref("Functions/arguments", "arguments")}} disponível nas função é usar simplesment a variável {{jsxref("Functions/arguments", "arguments")}}.

- -

No caso de recursão isto é, se uma funão f aparece várias vezes na stack, o valor de f.arguments representa os argumentos correspondentes à mais recente chamada da função.

- -

O valor da propriedade arguments é tipicamente null se não há nenuma invocação da função a acontecer, ou seja, a função foi chamada mas ainda não retornou.

- -

Exemplos

- -
function f(n) { g(n - 1); }
-
-function g(n) {
-  console.log('antes: ' + g.arguments[0]);
-  if (n > 0) { f(n); }
-  console.log('depois: ' + g.arguments[0]);
-}
-
-f(2);
-
-console.log('retornado: ' + g.arguments);
-
-// Output
-
-// antes: 1
-// antes: 0
-// depois: 0
-// depois: 1
-// retornado: null
-
- -

Especificações

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}} -

Definição inicial. Implementado em JavaScript 1.0. Tornado obsoleto a favor de {{jsxref("Functions/arguments", "arguments")}} em ES3.

-
{{SpecName('ES5.1', '#sec-10.6', 'arguments object')}}{{Spec2('ES5.1')}}Objecto {{jsxref("Functions/arguments", "arguments")}}
{{SpecName('ES6', '#sec-arguments-object', 'arguments object')}}{{Spec2('ES6')}}Objecto {{jsxref("Functions/arguments", "arguments")}}
{{SpecName('ESDraft', '#sec-arguments-object', 'arguments object')}}{{Spec2('ESDraft')}}Objecto {{jsxref("Functions/arguments", "arguments")}}
- -

Compatibilidade navegadores

- -
- - -

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

-
- -

Ver também

- - diff --git a/files/pt-pt/web/javascript/reference/global_objects/function/call/index.html b/files/pt-pt/web/javascript/reference/global_objects/function/call/index.html deleted file mode 100644 index fa3faee130..0000000000 --- a/files/pt-pt/web/javascript/reference/global_objects/function/call/index.html +++ /dev/null @@ -1,164 +0,0 @@ ---- -title: Function.prototype.call() -slug: Web/JavaScript/Reference/Global_Objects/Function/call -tags: - - Function - - JavaScript - - metodo -translation_of: Web/JavaScript/Reference/Global_Objects/Function/call ---- -
{{JSRef}}
- -

O método call() realiza a chamada de uma função com o parâmetros this além de outros parâmetros fornecidos individualmente.

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

Sintaxe

- -
func.call([thisArg[, arg1, arg2, ...argN]])
- -

Parâmetros

- -
-
thisArg {{optional_inline}}
-
O valor de this fornecido ao chamar func.
-
- -
-

Aviso: Em certos casos, thisArg pode não ser o valor que o método vê.

- -

Se o método for uma função em {{jsxref("Strict_mode", "non-strict mode", "", 1)}}, {{jsxref("Global_Objects/null", "null")}} e {{jsxref("Global_Objects/undefined", "undefined")}} são substituídos pelo objeto global, e valores primitivos são convertidos em objetos.

-
- -
-
arg1, arg2, ...argN {{optional_inline}}
-
Parâmetros para a função.
-
- -

Resultado

- -

O resultado ao chamar a função em questão com os parâmetros this e os outros argumentos especificados.

- -

Descrição

- -

call() permite uma função / método pertencendo a um objeto, ser atribuída a outro objeto e ser chamada desse mesmo.

- -

call() fornece um novo valor para this à função / método. Com call(), pode escrever um método uma vez, e depois herdar o método noutro objeto, sem ter de rescrever a função para o novo objeto.

- -
-

Nota: Apesar de a sintaxe da função ser quase idêntica à da {{jsxref("Function.prototype.apply", "apply()")}}, a principal diferença é que call() aceita uma lista de argumentos (arg1, arg2, ...argN), enquanto apply() aceita uma matriz de argumentos ([arg1, arg2, ...argN]).

-
- -

Exemplos

- -

Usar call para encadear construtores dum objeto

- -

É possível utilizar call para encadear construtores para um objeto (como em Java).

- -

No exemplo abaixo, o construtor para o objeto Product é definido com dois parâmetros: name e price.

- -

Duas outras funções, Food e Toy, invocam Product passando os parâmetros thisname e price. As funções Food e Toy também definem a propriadade category.

- -
function Product(name, price) {
-  this.name = name;
-  this.price = price;
-}
-
-function Food(name, price) {
-  Product.call(this, name, price);
-  this.category = 'food';
-}
-
-function Toy(name, price) {
-  Product.call(this, name, price);
-  this.category = 'toy';
-}
-
-const cheese = new Food('feta', 5);
-const fun = new Toy('robot', 40);
- -

Usar call para invocar uma função anónima

- -

Neste exemplo, criamos uma função anónima e utilizamos call para invocá-la em cada objeto na matriz.

- -

O principal objetivo da função anónima é inserir a função print em cada objeto. A função print imprimir o índice do objeto na matriz em que se encontra.

- -
-

Passar o objeto desta forma (como this) não é necessário, mas foi feito de forma a exemplificar a função.

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

Usar call para invocar a função sem especificar o primeiro argumento

- -

No exemplo abaixo, quando chamamos a função display sem passar o primeiro argumento. Se o primeiro argumento não é especificado, o objeto global é atribuído a this.
-  

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

Aviso: Em "strict mode", o valor de this é undefined, exemplificado em baixo.

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

Especificações

- - - - - - - - - - - - -
Especificação
{{SpecName('ESDraft', '#sec-function.prototype.call', 'Function.prototype.call')}}
- -

Browser compatibility

- - - -

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

- -

Veja também

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

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

- -

Syntax

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

Parameters

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

Description

- -

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

- -

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

- -

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

- -

Properties and Methods of Function

- -

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

- -

Function prototype object

- -

Properties

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

Methods

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

Function instances

- -

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

- -

Examples

- -

Specifying arguments with the Function constructor

- -

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

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

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

- -

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

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

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

See also

- - diff --git a/files/pt-pt/web/javascript/reference/global_objects/index.html b/files/pt-pt/web/javascript/reference/global_objects/index.html deleted file mode 100644 index f3850bdfd2..0000000000 --- a/files/pt-pt/web/javascript/reference/global_objects/index.html +++ /dev/null @@ -1,173 +0,0 @@ ---- -title: Objetos integrados padrão -slug: Web/JavaScript/Reference/Global_Objects -tags: - - Built-in - - JavaScript - - Objects - - Reference -translation_of: Web/JavaScript/Reference/Global_Objects ---- -
{{jsSidebar("Objects")}}
- -

Resumo

- -

Este capítulo documenta todos os objectos built-in do JavaScript standard, juntamente com os seus métodos e propriedades.

- -
-

O termo "objectos globais" (ou objectos built-in standard) não é para ser confundido com objecto global. Aqui, os objectos globais referem-se a objectos no scope global (mas apenas se o modo strict do ECMAScript 5 não estiver a ser usado! Senão retorna undefined). O próprio global object pode ser acedido através do operador {{jsxref("Operators/this", "this")}} no scope global. Na verdade, o scope global consiste nas propriedades do objecto global (incluíndo propriedades herdadas, se alguma).

- -

Outros objectos no scope global são criados através do script do utilizador or fornecidos pela aplicação host. Os objectos do host disponíveis no contexto browser são documentados na referência da API. Para mais informações sobre a distinção entre DOM e o núcleo do JavaScript, ver exposição das tecnologias do JavaScript.

- -

Objetos padrão (por categoria)

- -

Propriedades do valor

- -

Estas propriedades globais devolvem um valor simples; estas não têm propriedades ou métodos.

- - - -

Propriedades da função

- -

Estas funções globais - funções que são chamadas no mundo ao invés de um objeto - devolvem diretamente os seus resultados para o chamador.

- - - -

Objetos fundamentais

- -

Estes são os objetos básicos, fundamentais, em que todos os outros objetos são baseados. Isto inclui objetos que representam objetos gerais, funções, e erros.

- - - -

Números e datas

- -

Objectos que lidam com números, datas e cálculos matemáticos.

- - - -

Processamento de texto

- -

Objectos para manipular texto.

- - - -

Coleções indexadas

- -

Coleções ordenadas por um indíce. Objectos do tipo array.

- - - -

Coleções por chave

- -

Coleções de objectos como chaves. Elementos iteráveis por ordem de inserção.

- - - -

Dados estruturados

- -

Buffers de dados e JavaScript Object Notation (JSON).

- - - -

Objectos de abstração de controlo

- - - -

Reflexão

- - - -

Internacionalização

- -

Adições ao núcleo do ECMAScript para funcionalidades de linguagens sensíveis.

- - - -

Objetos não padrão

- - - -

Outros

- - -
- -

 

diff --git a/files/pt-pt/web/javascript/reference/global_objects/infinity/index.html b/files/pt-pt/web/javascript/reference/global_objects/infinity/index.html deleted file mode 100644 index 818471e60e..0000000000 --- a/files/pt-pt/web/javascript/reference/global_objects/infinity/index.html +++ /dev/null @@ -1,69 +0,0 @@ ---- -title: Infinity -slug: Web/JavaScript/Reference/Global_Objects/Infinity -tags: - - JavaScript - - Propriedade - - Referencia -translation_of: Web/JavaScript/Reference/Global_Objects/Infinity ---- -
{{jsSidebar("Objects")}}
- -

A propriedade global Infinity é um valor numérico que representa o infinito.

- -

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

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

Descrição

- -

Infinity é uma propriedade do objeto global. Isto é para dizer que é um variável com um escopo global.

- -

O valor inicial do Infinity é {{jsxref("Number.POSITIVE_INFINITY")}}. O valor Infinity (infinito positivo) é maior que qualquer outro número.

- -

Este valor age de form diferente do infinito matematico; veja {{jsxref("Number.POSITIVE_INFINITY")}} para mais detalhes.

- -

Como definido na especificação ECMAScript 5, Infinity é read-only (implementado em JavaScript 1.8.5 / Firefox 4).

- -

Exemplos

- -

Usar Infinity

- -
console.log(Infinity          ); /* Infinity */
-console.log(Infinity + 1      ); /* Infinity */
-console.log(Math.pow(10, 1000)); /* Infinity */
-console.log(Math.log(0)       ); /* -Infinity */
-console.log(1 / Infinity      ); /* 0 */
-console.log(1 / 0             ); /* Infinity */
-
- -

Especificações

- - - - - - - - - - - - -
Especificação
{{SpecName('ESDraft', '#sec-value-properties-of-the-global-object-infinity', 'Infinity')}}
- -

Compatibilidade

- - - -

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

- -

Veja também

- - diff --git a/files/pt-pt/web/javascript/reference/global_objects/math/ceil/index.html b/files/pt-pt/web/javascript/reference/global_objects/math/ceil/index.html deleted file mode 100644 index c89b15567a..0000000000 --- a/files/pt-pt/web/javascript/reference/global_objects/math/ceil/index.html +++ /dev/null @@ -1,161 +0,0 @@ ---- -title: Math.ceil() -slug: Web/JavaScript/Reference/Global_Objects/Math/ceil -translation_of: Web/JavaScript/Reference/Global_Objects/Math/ceil ---- -
{{JSRef}}
- -

A função Math.ceil() retorna um inteiro smallest (sem casas decimais) maior ou igual ao n.º passado como parâmetro. Por exemplo ao fazer Math.ceil(3.01) o valor retornado é 4, ao fazer Math.ceil(-5.01) o retorno é -5, ao fazer Math.ceil(7) o valor devolvido é 7. 

- -

Sintaxe

- -
Math.ceil(x)
- -

Parametros

- -
-
x
-
Um número.
-
- -

Valor de retorno

- -

Um inteiro smallest maior ou igual ao n.º passado como parâmetro.

- -

Descrição

- -

Como ceil() é um método estático de  Math,  pode sempre ser usado como Math.ceil(), o objeto Math não é um construtor. 

- -

Exemplos

- -

Utilizando Math.ceil()

- -

Seguem exemplos da utilização de Math.ceil().

- -
Math.ceil(.95);    // 1
-Math.ceil(4);      // 4
-Math.ceil(7.004);  // 8
-Math.ceil(-0.95);  // -0
-Math.ceil(-4);     // -4
-Math.ceil(-7.004); // -7
-
- -

Ajustamento decimal 

- -
// Closure
-(function() {
-  /**
-   * Decimal adjustment of a number.
-   *
-   * @param {String}  type  The type of adjustment.
-   * @param {Number}  value The number.
-   * @param {Integer} exp   The exponent (the 10 logarithm of the adjustment base).
-   * @returns {Number} The adjusted value.
-   */
-  function decimalAdjust(type, value, exp) {
-    // If the exp is undefined or zero...
-    if (typeof exp === 'undefined' || +exp === 0) {
-      return Math[type](value);
-    }
-    value = +value;
-    exp = +exp;
-    // If the value is not a number or the exp is not an integer...
-    if (isNaN(value) || !(typeof exp === 'number' && exp % 1 === 0)) {
-      return NaN;
-    }
-    // Shift
-    value = value.toString().split('e');
-    value = Math[type](+(value[0] + 'e' + (value[1] ? (+value[1] - exp) : -exp)));
-    // Shift back
-    value = value.toString().split('e');
-    return +(value[0] + 'e' + (value[1] ? (+value[1] + exp) : exp));
-  }
-
-  // Decimal round
-  if (!Math.round10) {
-    Math.round10 = function(value, exp) {
-      return decimalAdjust('round', value, exp);
-    };
-  }
-  // Decimal floor
-  if (!Math.floor10) {
-    Math.floor10 = function(value, exp) {
-      return decimalAdjust('floor', value, exp);
-    };
-  }
-  // Decimal ceil
-  if (!Math.ceil10) {
-    Math.ceil10 = function(value, exp) {
-      return decimalAdjust('ceil', value, exp);
-    };
-  }
-})();
-
-// Round
-Math.round10(55.55, -1);   // 55.6
-Math.round10(55.549, -1);  // 55.5
-Math.round10(55, 1);       // 60
-Math.round10(54.9, 1);     // 50
-Math.round10(-55.55, -1);  // -55.5
-Math.round10(-55.551, -1); // -55.6
-Math.round10(-55, 1);      // -50
-Math.round10(-55.1, 1);    // -60
-// Floor
-Math.floor10(55.59, -1);   // 55.5
-Math.floor10(59, 1);       // 50
-Math.floor10(-55.51, -1);  // -55.6
-Math.floor10(-51, 1);      // -60
-// Ceil
-Math.ceil10(55.51, -1);    // 55.6
-Math.ceil10(51, 1);        // 60
-Math.ceil10(-55.59, -1);   // -55.5
-Math.ceil10(-59, 1);       // -50
-
- -

Especificações 

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationEstadoComentário
{{SpecName('ES1')}}{{Spec2('ES1')}}Definição inicial JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.8.2.6', 'Math.ceil')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-math.ceil', 'Math.ceil')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-math.ceil', 'Math.ceil')}}{{Spec2('ESDraft')}}
- -

Browser compatibility

- - - -

{{Compat("javascript.builtins.Math.ceil")}}

- -

See also

- - diff --git a/files/pt-pt/web/javascript/reference/global_objects/math/index.html b/files/pt-pt/web/javascript/reference/global_objects/math/index.html deleted file mode 100644 index 867c783782..0000000000 --- a/files/pt-pt/web/javascript/reference/global_objects/math/index.html +++ /dev/null @@ -1,214 +0,0 @@ ---- -title: Math -slug: Web/JavaScript/Reference/Global_Objects/Math -translation_of: Web/JavaScript/Reference/Global_Objects/Math ---- -
{{JSRef}}
- -

Math é um objecto integrado que tem propriedades e métodos correspondentes a constantes e funções matemáticas. Não é um objecto função.

- -

Descrição

- -

Contrariamente aos outros objectos globais, Math não é um construtor. Todas as propriedades e métodos de Math são estáticas. Refere-se a constante pi com Math.PI e chama-se a função de seno com Math.sin(x), em que x é o argumento do método. As constantes estão definidas com a precisão completa dos números reais do JavaScript.

- -

Para extender o objecto Math, não se usa o protótipo. Em vez disso extende-se directamente o objecto Math:

- -

Math.nomeProp=valorProp;

- -

Math.nomeMetodo=refMetodo;

- -

Propriedades

- -
-
{{jsxref("Math.E")}}
-
Euler's constant and the base of natural logarithms, approximately 2.718.
-
{{jsxref("Math.LN2")}}
-
Natural logarithm of 2, approximately 0.693.
-
{{jsxref("Math.LN10")}}
-
Natural logarithm of 10, approximately 2.303.
-
{{jsxref("Math.LOG2E")}}
-
Base 2 logarithm of E, approximately 1.443.
-
{{jsxref("Math.LOG10E")}}
-
Base 10 logarithm of E, approximately 0.434.
-
{{jsxref("Math.PI")}}
-
Ratio of the circumference of a circle to its diameter, approximately 3.14159.
-
{{jsxref("Math.SQRT1_2")}}
-
Square root of 1/2; equivalently, 1 over the square root of 2, approximately 0.707.
-
{{jsxref("Math.SQRT2")}}
-
Square root of 2, approximately 1.414.
-
- -

Métodos

- -
-

Note that the trigonometric functions (sin(), cos(), tan(), asin(), acos(), atan(), atan2()) expect or return angles in radians. To convert radians to degrees, divide by (Math.PI / 180), and multiply by this to convert the other way.

-
- -
-

Note that many math functions have a precision that's implementation-dependent. This means that different browsers can give a different result, and even the same JS engine on a different OS or architecture can give different results.

-
- -
-
{{jsxref("Global_Objects/Math/abs", "Math.abs(x)")}}
-
Returns the absolute value of a number.
-
{{jsxref("Global_Objects/Math/acos", "Math.acos(x)")}}
-
Returns the arccosine of a number.
-
{{jsxref("Global_Objects/Math/acosh", "Math.acosh(x)")}}
-
Returns the hyperbolic arccosine of a number.
-
{{jsxref("Global_Objects/Math/asin", "Math.asin(x)")}}
-
Returns the arcsine of a number.
-
{{jsxref("Global_Objects/Math/asinh", "Math.asinh(x)")}}
-
Returns the hyperbolic arcsine of a number.
-
{{jsxref("Global_Objects/Math/atan", "Math.atan(x)")}}
-
Returns the arctangent of a number.
-
{{jsxref("Global_Objects/Math/atanh", "Math.atanh(x)")}}
-
Returns the hyperbolic arctangent of a number.
-
{{jsxref("Global_Objects/Math/atan2", "Math.atan2(y, x)")}}
-
Returns the arctangent of the quotient of its arguments.
-
{{jsxref("Global_Objects/Math/cbrt", "Math.cbrt(x)")}}
-
Returns the cube root of a number.
-
{{jsxref("Global_Objects/Math/ceil", "Math.ceil(x)")}}
-
Returns the smallest integer greater than or equal to a number.
-
{{jsxref("Global_Objects/Math/clz32", "Math.clz32(x)")}}
-
Returns the number of leading zeroes of a 32-bit integer.
-
{{jsxref("Global_Objects/Math/cos", "Math.cos(x)")}}
-
Returns the cosine of a number.
-
{{jsxref("Global_Objects/Math/cosh", "Math.cosh(x)")}}
-
Returns the hyperbolic cosine of a number.
-
{{jsxref("Global_Objects/Math/exp", "Math.exp(x)")}}
-
Returns Ex, where x is the argument, and E is Euler's constant (2.718…), the base of the natural logarithm.
-
{{jsxref("Global_Objects/Math/expm1", "Math.expm1(x)")}}
-
Returns subtracting 1 from exp(x).
-
{{jsxref("Global_Objects/Math/floor", "Math.floor(x)")}}
-
Returns the largest integer less than or equal to a number.
-
{{jsxref("Global_Objects/Math/fround", "Math.fround(x)")}}
-
Returns the nearest single precision float representation of a number.
-
{{jsxref("Global_Objects/Math/hypot", "Math.hypot([x[, y[, …]]])")}}
-
Returns the square root of the sum of squares of its arguments.
-
{{jsxref("Global_Objects/Math/imul", "Math.imul(x, y)")}}
-
Returns the result of a 32-bit integer multiplication.
-
{{jsxref("Global_Objects/Math/log", "Math.log(x)")}}
-
Returns the natural logarithm (loge, also ln) of a number.
-
{{jsxref("Global_Objects/Math/log1p", "Math.log1p(x)")}}
-
Returns the natural logarithm (loge, also ln) of 1 + x for a number x.
-
{{jsxref("Global_Objects/Math/log10", "Math.log10(x)")}}
-
Returns the base 10 logarithm of a number.
-
{{jsxref("Global_Objects/Math/log2", "Math.log2(x)")}}
-
Returns the base 2 logarithm of a number.
-
{{jsxref("Global_Objects/Math/max", "Math.max([x[, y[, …]]])")}}
-
Returns the largest of zero or more numbers.
-
{{jsxref("Global_Objects/Math/min", "Math.min([x[, y[, …]]])")}}
-
Returns the smallest of zero or more numbers.
-
{{jsxref("Global_Objects/Math/pow", "Math.pow(x, y)")}}
-
Returns base to the exponent power, that is, baseexponent.
-
{{jsxref("Global_Objects/Math/random", "Math.random()")}}
-
Returns a pseudo-random number between 0 and 1.
-
{{jsxref("Global_Objects/Math/round", "Math.round(x)")}}
-
Returns the value of a number rounded to the nearest integer.
-
{{jsxref("Global_Objects/Math/sign", "Math.sign(x)")}}
-
Returns the sign of the x, indicating whether x is positive, negative or zero.
-
{{jsxref("Global_Objects/Math/sin", "Math.sin(x)")}}
-
Returns the sine of a number.
-
{{jsxref("Global_Objects/Math/sinh", "Math.sinh(x)")}}
-
Returns the hyperbolic sine of a number.
-
{{jsxref("Global_Objects/Math/sqrt", "Math.sqrt(x)")}}
-
Returns the positive square root of a number.
-
{{jsxref("Global_Objects/Math/tan", "Math.tan(x)")}}
-
Returns the tangent of a number.
-
{{jsxref("Global_Objects/Math/tanh", "Math.tanh(x)")}}
-
Returns the hyperbolic tangent of a number.
-
Math.toSource() {{non-standard_inline}}
-
Returns the string "Math".
-
{{jsxref("Global_Objects/Math/trunc", "Math.trunc(x)")}}
-
Returns the integral part of the number x, removing any fractional digits.
-
- -

Especificações

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.8', 'Math')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math-object', 'Math')}}{{Spec2('ES6')}}New methods {{jsxref("Math.log10()", "log10()")}}, {{jsxref("Math.log2()", "log2()")}}, {{jsxref("Math.log1p()", "log1p()")}}, {{jsxref("Math.expm1()", "expm1()")}}, {{jsxref("Math.cosh()", "cosh()")}}, {{jsxref("Math.sinh()", "sinh()")}}, {{jsxref("Math.tanh()", "tanh()")}}, {{jsxref("Math.acosh()", "acosh()")}}, {{jsxref("Math.asinh()", "asinh()")}}, {{jsxref("Math.atanh()", "atanh()")}}, {{jsxref("Math.hypot()", "hypot()")}}, {{jsxref("Math.trunc()", "trunc()")}}, {{jsxref("Math.sign()", "sign()")}}, {{jsxref("Math.imul()", "imul()")}}, {{jsxref("Math.fround()", "fround()")}}, {{jsxref("Math.cbrt()", "cbrt()")}} and {{jsxref("Math.clz32()", "clz32()")}} added.
{{SpecName('ESDraft', '#sec-math-object', 'Math')}}{{Spec2('ESDraft')}} 
- -

Browser compatibility

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

See also

- - diff --git a/files/pt-pt/web/javascript/reference/global_objects/number/index.html b/files/pt-pt/web/javascript/reference/global_objects/number/index.html deleted file mode 100644 index 9ac8497a44..0000000000 --- a/files/pt-pt/web/javascript/reference/global_objects/number/index.html +++ /dev/null @@ -1,213 +0,0 @@ ---- -title: Number -slug: Web/JavaScript/Reference/Global_Objects/Number -tags: - - JavaScript - - Number - - Reference - - TopicStub -translation_of: Web/JavaScript/Reference/Global_Objects/Number ---- -
{{JSRef}}
- -

O objecto JavaScript Number é um objecto abstraído que te permite trabalhar com valores numéricos. Um objecto Number é criado usando o constructor Number().

- -

Constructor

- -
new Number(valor);
- -

Parâmetro

- -
-
valor
-
O valor numérico representado pelo objecto que está a ser criado.
-
- -

Descrição

- -

Os usos mais comuns para o objecto Number são:

- - - -

Propriedades

- -
-
{{jsxref("Number.EPSILON")}} {{experimental_inline}}
-
O intervalo mais pequeno entre dois números representáveis.
-
{{jsxref("Number.MAX_SAFE_INTEGER")}} {{experimental_inline}}
-
O maior inteiro bem representado em JavaScript (253 - 1).
-
{{jsxref("Number.MAX_VALUE")}}
-
O maior número positivo representável.
-
{{jsxref("Number.MIN_SAFE_INTEGER")}} {{experimental_inline}}
-
O menor inteiro bem representado em JavaScript (-(253 - 1)).
-
{{jsxref("Number.MIN_VALUE")}}
-
O menor número positivo representável - ou seja, o número positivo mais próximo de zero (sem ser o zero).
-
{{jsxref("Number.NaN")}}
-
Valor especial para representar um "não número".
-
{{jsxref("Number.NEGATIVE_INFINITY")}}
-
Valor especial para representar o infinito negativo; retornado em caso de overflow.
-
{{jsxref("Number.POSITIVE_INFINITY")}}
-
Valor especial para representar o infinito; retornado em caso de overflow.
-
{{jsxref("Number.prototype")}}
-
Permite adicionar propriedades ao objecto Number.
-
- -

Métodos

- -
-
{{jsxref("Number.isNaN()")}} {{experimental_inline}}
-
Determina se o valor passado é NaN.
-
{{jsxref("Number.isFinite()")}} {{experimental_inline}}
-
Determina se o valor passado é um número finito.
-
{{jsxref("Number.isInteger()")}} {{experimental_inline}}
-
Determina se o número passado é um inteiro.
-
{{jsxref("Number.isSafeInteger()")}} {{experimental_inline}}
-
Determina se o valor passado é um inteiro bem representado (número entre -(253 - 1) e 253 - 1).
-
{{jsxref("Number.toInteger()")}} {{obsolete_inline}}
-
Usado para avaliar o valor passado e convertê-lo num inteiro (ou {{jsxref("Global_Objects/Infinity", "Infinity")}}), mas foi removido.
-
{{jsxref("Number.parseFloat()")}} {{experimental_inline}}
-
O valor é o mesmo que {{jsxref("Global_Objects/parseFloat", "parseFloat()")}} de um objecto global.
-
{{jsxref("Number.parseInt()")}} {{experimental_inline}}
-
O valor é o mesmo que {{jsxref("Global_Objects/parseInt", "parseInt()")}} de um objecto global.
-
- -

Instâncias de Number

- -

Todas as instâncias de Number herdam de {{jsxref("Number.prototype")}}. O objecto protótipo (prototype) do constructor de Number pode ser modificado para afectar todas as instâncias de Number.

- -

Métodos

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

Exemplos

- -

Usar  o objecto Number para atribuír valores a variáveis numéricas

- -

O seguinte exemplo usa as propriedades do objecto Number para atribuír valores a várias variáveis numéricas: 

- -
var biggestNum = Number.MAX_VALUE;
-var smallestNum = Number.MIN_VALUE;
-var infiniteNum = Number.POSITIVE_INFINITY;
-var negInfiniteNum = Number.NEGATIVE_INFINITY;
-var notANum = Number.NaN;
-
- -

Limite inteiro para Number

- -

O seguinte exemplo mostra o mínimo e máximo valores inteiros que podem ser representados como um objecto Number (para mais detalhes, consulta o standard do ECMAScript, capítulo 8.5 The Number Type):

- -
var biggestInt = 9007199254740992;
-var smallestInt = -9007199254740992;
-
- -

Ao analisar dados que foram serializados para JSON, os valores inteiros fora deste limite são expectáveis de ficar corrompidos quando o analisador de JSON os tentar converter para o tipo Number. Como possível alternativa, usa {{jsxref("String")}}.

- -

Usar Number para converter um objecto Date

- -

O seguinte exemplo converte o objecto {{jsxref("Date")}} num valor numérico usando Number como função:

- -
var d = new Date('December 17, 1995 03:24:00');
-console.log(Number(d));
-
- -

Este código imprime "819199440000".

- -

Converter strings numéricas para números

- -
Number("123")     // 123
-Number("")        // 0
-Number("0x11")    // 17
-Number("0b11")    // 3
-Number("0o11")    // 9
-Number("foo")     // NaN
-Number("100a")    // NaN
-
- -

Especificações

- - - - - - - - - - - - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName('ES1')}}{{Spec2('ES1')}}Definição inicial. Implementado em JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.7', 'Number')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-number-objects', 'Number')}}{{Spec2('ES6')}}Adicionados novas propriedades e métodos: ({{jsxref("Number.EPSILON", "EPSILON")}}, {{jsxref("Number.isFinite", "isFinite")}}, {{jsxref("Number.isInteger", "isInteger")}}, {{jsxref("Number.isNaN", "isNaN")}}, {{jsxref("Number.parseFloat", "parseFloat")}}, {{jsxref("Number.parseInt", "parseInt")}})
- -

Compatibilidade dos browsers

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FuncionalidadeChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FuncionalidadeAndroidChrome para AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Ver também

- - diff --git a/files/pt-pt/web/javascript/reference/global_objects/number/isfinite/index.html b/files/pt-pt/web/javascript/reference/global_objects/number/isfinite/index.html deleted file mode 100644 index 9b70ca6a98..0000000000 --- a/files/pt-pt/web/javascript/reference/global_objects/number/isfinite/index.html +++ /dev/null @@ -1,126 +0,0 @@ ---- -title: Number.isFinite() -slug: Web/JavaScript/Reference/Global_Objects/Number/isFinite -tags: - - Experimental - - Finite - - JavaScript - - Method - - Método(2) - - Number - - Reference -translation_of: Web/JavaScript/Reference/Global_Objects/Number/isFinite ---- -
{{JSRef}}
- -

O método Number.isFinite() determina se o valor passado é um número finito.

- -

Sintaxe

- -
Number.isFinite(valor)
- -

Parâmetros

- -
-
valor
-
O valor a ser testado.
-
- -

Descrição

- -

Em comparação com a função global {{jsxref("Global_Objects/isFinite", "isFinite()")}}, Number.isFinite() não converte forçosamente o parâmetro num number. Isto significa que apenas para valores do tipo number, finitos, retorna true.

- -

Exemplos

- -
Number.isFinite(Infinity);  // false
-Number.isFinite(NaN);       // false
-Number.isFinite(-Infinity); // false
-
-Number.isFinite(0);         // true
-Number.isFinite(2e64);      // true
-
-Number.isFinite('0');       // false, teria sido true com a função
-                            // global isFinite('0')
-
- -

Polyfill

- -
Number.isFinite = Number.isFinite || function(value) {
-    return typeof value === "number" && isFinite(value);
-}
-
- -

Especificações

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES6', '#sec-number.isfinite', 'Number.isInteger')}}{{Spec2('ES6')}}Initial definition.
- -

Compatibilidade dos browsers

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FuncionalidadeChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{CompatChrome("19")}}{{CompatGeckoDesktop("16")}}{{CompatNo}}{{CompatOpera("15")}}{{CompatNo}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FuncionalidadeAndroidChrome para AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("16")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -

Ver também

- - diff --git a/files/pt-pt/web/javascript/reference/global_objects/number/isinteger/index.html b/files/pt-pt/web/javascript/reference/global_objects/number/isinteger/index.html deleted file mode 100644 index 8c6dc79bb7..0000000000 --- a/files/pt-pt/web/javascript/reference/global_objects/number/isinteger/index.html +++ /dev/null @@ -1,125 +0,0 @@ ---- -title: Number.isInteger() -slug: Web/JavaScript/Reference/Global_Objects/Number/isInteger -tags: - - Experimental - - JavaScript - - Method - - Método(2) - - Number - - Reference -translation_of: Web/JavaScript/Reference/Global_Objects/Number/isInteger ---- -
{{JSRef}}
- -

O método Number.isInteger() determina se o valor passado é um inteiro.

- -

Sintaxe

- -
Number.isInteger(valor)
- -

Parâmteros

- -
-
valor
-
O valor a ser testado por ser um inteiro.
-
- -

Descrição

- -

Se o valor a ser testado for um inteiro, retorna true, senão retorna false. Se o valor for {{jsxref("Global_Objects/NaN", "NaN")}} ou infinito, retorna false.

- -

Exemplos

- -
Number.isInteger(0.1);     // false
-Number.isInteger(1);       // true
-Number.isInteger(Math.PI); // false
-Number.isInteger(-100000); // true
-Number.isInteger(NaN);     // false
-Number.isInteger(0);       // true
-Number.isInteger("10");    // false
-
- -

Polyfill

- -
Number.isInteger = Number.isInteger || function(value) {
-    return typeof value === "number" &&
-           isFinite(value) &&
-           Math.floor(value) === value;
-};
-
- -

Especificações

- - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName('ES6', '#sec-number.isinteger', 'Number.isInteger')}}{{Spec2('ES6')}}Definição inicial.
- -

Compatibilidade dos browsers

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FuncionalidadeChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{CompatVersionUnknown}}{{CompatGeckoDesktop("16")}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FuncionalidadeAndroidChrome para AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile("16")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
- -

Ver também

- - diff --git a/files/pt-pt/web/javascript/reference/global_objects/number/isnan/index.html b/files/pt-pt/web/javascript/reference/global_objects/number/isnan/index.html deleted file mode 100644 index 0b242adbbe..0000000000 --- a/files/pt-pt/web/javascript/reference/global_objects/number/isnan/index.html +++ /dev/null @@ -1,136 +0,0 @@ ---- -title: Number.isNaN() -slug: Web/JavaScript/Reference/Global_Objects/Number/isNaN -tags: - - ECMAScript6 - - Experimental - - JavaScript - - Method - - Método(2) - - Number -translation_of: Web/JavaScript/Reference/Global_Objects/Number/isNaN ---- -
{{JSRef}}
- -

O método Number.isNaN() determina se o valor passado é {{jsxref("Global_Objects/NaN", "NaN")}}. Esta é uma versão mais robusta que {{jsxref("Global_Objects/isNaN", "isNaN()")}}.

- -

Sintaxe

- -
Number.isNaN(valor)
- -

Parâmetros

- -
-
valor
-
O valor a ser testado se é {{jsxref("Global_Objects/NaN", "NaN")}}.
-
- -

Descrição

- -

Due to both equality operators, {{jsxref("Operators/Comparison_Operators", "==", "#Equality")}} and {{jsxref("Operators/Comparison_Operators", "===", "#Identity")}}, evaluating to false when checking if {{jsxref("Global_Objects/NaN", "NaN")}} is {{jsxref("Global_Objects/NaN", "NaN")}}, the function Number.isNaN() has become necessary. This situation is unlike all other possible value comparisons in JavaScript.

- -

In comparison to the global {{jsxref("Global_Objects/isNaN", "isNaN()")}} function, Number.isNaN() doesn't suffer the problem of forcefully converting the parameter to a number. This means it is now safe to pass values that would normally convert to {{jsxref("Global_Objects/NaN", "NaN")}}, but aren't actually the same value as {{jsxref("Global_Objects/NaN", "NaN")}}. This also means that only values of the type number, that are also {{jsxref("Global_Objects/NaN", "NaN")}}, return true.

- -

Exemplos

- -
Number.isNaN(NaN);        // true
-Number.isNaN(Number.NaN); // true
-Number.isNaN(0 / 0)       // true
-
-// e.g. these would have been true with global isNaN()
-Number.isNaN("NaN");      // false
-Number.isNaN(undefined);  // false
-Number.isNaN({});         // false
-Number.isNaN("blabla");   // false
-
-// These all return false
-Number.isNaN(true);
-Number.isNaN(null);
-Number.isNaN(37);
-Number.isNaN("37");
-Number.isNaN("37.37");
-Number.isNaN("");
-Number.isNaN(" ");
-
- -

Polyfill

- -
Number.isNaN = Number.isNaN || function(value) {
-    return typeof value === "number" && isNaN(value);
-}
- -

Especificações

- - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName('ES6', '#sec-number.isnan', 'Number.isnan')}}{{Spec2('ES6')}}Definição inicial.
- -

Compatibilidade dos browsers

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FuncionalidadeChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("25")}}{{CompatGeckoDesktop("15")}}{{CompatNo}}{{CompatVersionUnknown}}9
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FuncionalidadeAndroidChrome para AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatUnknown}}{{CompatGeckoMobile("15")}}{{CompatNo}}{{CompatNo}}iOS 9+
-
- -

Ver também

- - diff --git a/files/pt-pt/web/javascript/reference/global_objects/number/max_value/index.html b/files/pt-pt/web/javascript/reference/global_objects/number/max_value/index.html deleted file mode 100644 index cd1666ecbc..0000000000 --- a/files/pt-pt/web/javascript/reference/global_objects/number/max_value/index.html +++ /dev/null @@ -1,119 +0,0 @@ ---- -title: Number.MAX_VALUE -slug: Web/JavaScript/Reference/Global_Objects/Number/MAX_VALUE -tags: - - JavaScript - - Number - - Property - - Propriedade -translation_of: Web/JavaScript/Reference/Global_Objects/Number/MAX_VALUE ---- -
{{JSRef}}
- -

A propriedade Number.MAX_VALUE representa o máximo valor numérico representável em JavaScript.

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

Descrição

- -

A propriedade MAX_VALUE tem um valor aproximado de 1.79E+308. Valores maiores do que MAX_VALUE são representados como "Infinity".

- -

Dado que MAX_VALUE é uma propriedade estática (static) de {{jsxref("Number")}}, tu deves sempre usá-la na forma Number.MAX_VALUE, em vez de na forma de uma propriedade de um objecto {{jsxref("Number")}}  que tenhas criado.

- -

Exemplos

- -

Usando MAX_VALUE

- -

O seguinte código multiplica dois valores numéricos. Se o resultado for inferior ou igual a MAX_VALUE, a função func1 é chamada; senão será chamada a função func2.

- -
if (num1 * num2 <= Number.MAX_VALUE) {
-  func1();
-} else {
-  func2();
-}
-
- -

Especificações

- - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Definição inicial. Implementado em JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.7.3.2', 'Number.MAX_VALUE')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-number.max_value', 'Number.MAX_VALUE')}}{{Spec2('ES6')}} 
- -

Compatibilidade dos browsers

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FuncionalidadeChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FuncionalidadeAndroidChrome para AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Ver também

- - diff --git a/files/pt-pt/web/javascript/reference/global_objects/number/min_value/index.html b/files/pt-pt/web/javascript/reference/global_objects/number/min_value/index.html deleted file mode 100644 index 852b37426b..0000000000 --- a/files/pt-pt/web/javascript/reference/global_objects/number/min_value/index.html +++ /dev/null @@ -1,121 +0,0 @@ ---- -title: Number.MIN_VALUE -slug: Web/JavaScript/Reference/Global_Objects/Number/MIN_VALUE -tags: - - JavaScript - - Number - - Property - - Propriedade -translation_of: Web/JavaScript/Reference/Global_Objects/Number/MIN_VALUE ---- -
{{JSRef}}
- -

A propriedade Number.MIN_VALUE representa o mínimo valor numérico representável em JavaScript.

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

Descrição

- -

A propriedade MIN_VALUE representa o valor mais próximo de 0 (zero), não negativo, que o JavaScript consegue representar.

- -

A propriedade MIN_VALUE tem um valor aproximado de 5e-324. Valores menores do que MIN_VALUE ("underflow values") são são convertidos para 0 (zero).

- -

Dado que MIN_VALUE é uma propriedade estática (static) de {{jsxref("Number")}}, tu deves sempre usá-la na forma Number.MIN_VALUE, em vez de na forma de uma propriedade de um objecto {{jsxref("Number")}} que tenhas criado.

- -

Exemplos

- -

Usando MIN_VALUE

- -

O seguinte código divide dois valores numéricos. Se o resultado for superior ou igual a MIN_VALUE, a função func1 é chamada; senão será chamada a função func2.

- -
if (num1 / num2 >= Number.MIN_VALUE) {
-  func1();
-} else {
-  func2();
-}
-
- -

Especificações

- - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.7.3.3', 'Number.MIN_VALUE')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-number.min_value', 'Number.MIN_VALUE')}}{{Spec2('ES6')}} 
- -

Compatibilidade dos browsers

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FuncionalidadeChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FuncionalidadeAndroidChrome para AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Ver também

- - diff --git a/files/pt-pt/web/javascript/reference/global_objects/number/nan/index.html b/files/pt-pt/web/javascript/reference/global_objects/number/nan/index.html deleted file mode 100644 index c3213486b7..0000000000 --- a/files/pt-pt/web/javascript/reference/global_objects/number/nan/index.html +++ /dev/null @@ -1,103 +0,0 @@ ---- -title: Number.NaN -slug: Web/JavaScript/Reference/Global_Objects/Number/NaN -tags: - - JavaScript - - Number - - Property - - Propriedade -translation_of: Web/JavaScript/Reference/Global_Objects/Number/NaN ---- -
{{JSRef}}
- -

A propriedade Number.NaN representa um Não-Número. Equivalente a {{jsxref("NaN")}}.

- -

Não precisas de criar um objecto {{jsxref("Number")}} para aceder a esta propriedade estática (static) (usa Number.NaN).

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

Especificações

- - - - - - - - - - - - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName('ES1')}}{{Spec2('ES1')}}Definição inicial. Implementado no JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.7.3.4', 'Number.NaN')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-number.nan', 'Number.NaN')}}{{Spec2('ES6')}} 
- -

Compatibilidade dos browsers

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FuncionalidadeChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FuncionalidadeAndroidChrome para AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Ver também

- - diff --git a/files/pt-pt/web/javascript/reference/global_objects/number/negative_infinity/index.html b/files/pt-pt/web/javascript/reference/global_objects/number/negative_infinity/index.html deleted file mode 100644 index a2a7d0f962..0000000000 --- a/files/pt-pt/web/javascript/reference/global_objects/number/negative_infinity/index.html +++ /dev/null @@ -1,91 +0,0 @@ ---- -title: Number.NEGATIVE_INFINITY -slug: Web/JavaScript/Reference/Global_Objects/Number/NEGATIVE_INFINITY -tags: - - JavaScript - - Number - - Propriedade - - Referencia -translation_of: Web/JavaScript/Reference/Global_Objects/Number/NEGATIVE_INFINITY ---- -
{{JSRef}}
- -

A propriedade Number.NEGATIVE_INFINITY representa o valor negativo Infinito.

- -

Não tem de criar um objecto {{jsxref("Number")}} para aceder a esta propriedade estática (usa Number.NEGATIVE_INFINITY).

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

Descrição

- -

O valor de Number.NEGATIVE_INFINITY é o mesmo que o valor negativo da propriedade {{jsxref("Infinity")}} do objeto global.

- -

Este valor comporta-se de forma ligeiramente diferente do infinito matemático:

- - - -

Pode usar a propriedade Number.NEGATIVE_INFINITY para indicar uma condição de erro numa situação em que, no caso de sucesso, é retornado um valor finito.

- -

Exemplos

- -

Usando NEGATIVE_INFINITY

- -

No seguinte exemplo, é atribuído à variável smallNumber um valor inferior ao valor mínimo. Quando a linha de código {{jsxref("Statements/if...else", "if")}} é executada, a variável smallNumber tem o valor -Infinity, então é atribuída à mesma variável um valor finito antes de continuar.

- -
var smallNumber = (-Number.MAX_VALUE) * 2;
-
-if (smallNumber == Number.NEGATIVE_INFINITY) {
-  smallNumber = returnFinite();
-}
-
- -

Especificações

- - - - - - - - - - - - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.7.3.5', 'Number.NEGATIVE_INFINITY')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-number.negative_infinity', 'Number.NEGATIVE_INFINITY')}}{{Spec2('ES6')}}
- -

Compatibilidade

- - - -

{{Compat("javascript.builtins.Number.NEGATIVE_INFINITY")}}

- -

Ver também

- - diff --git a/files/pt-pt/web/javascript/reference/global_objects/number/tostring/index.html b/files/pt-pt/web/javascript/reference/global_objects/number/tostring/index.html deleted file mode 100644 index 1ff4892314..0000000000 --- a/files/pt-pt/web/javascript/reference/global_objects/number/tostring/index.html +++ /dev/null @@ -1,146 +0,0 @@ ---- -title: Number.prototype.toString() -slug: Web/JavaScript/Reference/Global_Objects/Number/toString -tags: - - JavaScript - - Number - - Prototype - - metodo -translation_of: Web/JavaScript/Reference/Global_Objects/Number/toString ---- -
{{JSRef}}
- -

O método toString() retorna  uma string com o valor do objecto {{jsxref("Number")}} especificado.

- -

Sintaxe

- -
numObj.toString([radix])
- -

Parâmetros

- -
-
base
-
Opcional. Um inteiro entre [2, 36] especificando a base usada para representar o valor númerico.
-
- -

Erros possíveis

- -
-
{{jsxref("RangeError")}}
-
Se o valor do parâmetro base não estiver entre [2, 36], o erro {{jsxref("RangeError")}} é lançado.
-
- -

Descrição

- -

O objecto {{jsxref("Number")}} faz override ao método toString() do objecto {{jsxref("Object")}}; não herda de {{jsxref("Object.prototype.toString()")}}. Para os objectos {{jsxref( "Number")}}, o método toString() retorna uma representação em string do ojecto na base especificada.

- -

O método toString() analisa o seu primeiro argumento e tenta retornar uma representação em string na base especificada. Para bases superiores a 10, as letras do alfabeto representam numerais maiores do que 9 (por ordem alfabética: a, b, c ...). Por exemplo, para números hexadecimais (base 16) são usadasa as letras do alfabeto até f.

- -

Se a base não for especificada, o seu valor assumido é 10.

- -

Se o numObj tem um valor negativo (< 0), o sinal é preservado. O mesmo se aplica se a base tiver o valor 2; a string retornada é a representação positiva do binário de numObj precedida pelo sinal negativo (-), e não complement para 2 de numObj.

- -

Exemplos

- -

Usando toString

- -
var count = 10;
-
-console.log(count.toString());    // imprime '10'
-console.log((17).toString());     // imprime '17'
-
-var x = 6;
-
-console.log(x.toString(2));       // imprime '110'
-console.log((254).toString(16));  // imprime 'fe'
-
-console.log((-10).toString(2));   // imprime '-1010'
-console.log((-0xff).toString(2)); // imprime'-11111111'
-
- -

Especificações

- - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Definição inicial. Implementado em JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.7.4.2', 'Number.prototype.tostring')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-number.prototype.tostring', 'Number.prototype.tostring')}}{{Spec2('ES6')}} 
- -

Compatibilidade dos browsers

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FuncionalidadeChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FuncionalidadeAndroidChrome para AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
BSuporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Ver também

- - diff --git a/files/pt-pt/web/javascript/reference/global_objects/object/hasownproperty/index.html b/files/pt-pt/web/javascript/reference/global_objects/object/hasownproperty/index.html deleted file mode 100644 index 2c91823404..0000000000 --- a/files/pt-pt/web/javascript/reference/global_objects/object/hasownproperty/index.html +++ /dev/null @@ -1,187 +0,0 @@ ---- -title: Object.prototype.hasOwnProperty() -slug: Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty -tags: - - JavaScript - - Objeto - - Prototipo - - metodo -translation_of: Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty ---- -
{{JSRef}}
- -

O método hasOwnProperty() retorna um booleano indicando se o objeto tem a propriedade especificada.

- -

Sintaxe

- -
obj.hasOwnProperty(prop)
- -

Parâmetros

- -
-
prop
-
O nome da propriedade para testar.
-
- -

Descrição

- -

Cada objecto descendente de {{jsxref("Object")}} herda o método hasOwnProperty. Este método pode ser usado para determinar se um objecto contém a propriedade especificada como uma propriedade direta desse objeto; ao contrário do operador {{jsxref("Operators/in", "in")}}, este método não verifica a cadeia de objetos do protótipo.

- -

Exemplos

- -

Usando hasOwnProperty para testar a existência de uma propriedade

- -

O seguinte exemplo determina se o objecto "o" contém a propriedade "prop":

- -
o = new Object();
-o.prop = 'existe';
-
-function changeO() {
-  o.newprop = o.prop;
-  delete o.prop;
-}
-
-o.hasOwnProperty('prop');   // retorna true
-changeO();
-o.hasOwnProperty('prop');   // retorna false
-
- -

Direto versus propriedades herdadas

- -

O seguinte exemplo diferencia entre propriedades diretas e propriedades herdadas através da cadeia de protótipos:

- -
o = new Object();
-o.prop = 'existe';
-o.hasOwnProperty('prop');             // retorna true
-o.hasOwnProperty('toString');         // retorna false
-o.hasOwnProperty('hasOwnProperty');   // retorna false
-
- -

Iteração entre as propriedades de um objeto

- -

O seguinte exemplo mostra como iterar entre as propriedades de um objeto sem executar em propriedades herdadas. Note que o ciclo {{jsxref("Statements/for...in", "for...in")}}  já está apenas repetindo itens enumeráveis então um não devia assumir baseado na falta de propriedades não-enumeráveis mostrado no ciclo que hasOwnProperty em si é estritamente limitado aos itens enumeráveis (como com {{jsxref("Object.getOwnPropertyNames()")}}).

- -
var buz = {
-  fog: 'stack'
-};
-
-for (var name in buz) {
-  if (buz.hasOwnProperty(name)) {
-    console.log('Isto é fog (' + name + ') com certeza. Valor: ' + buz[name]);
-  }
-  else {
-    console.log(name); // toString ou outra coisa
-  }
-}
-
- -

Usando hasOwnProperty como um nome de uma propriedade

- -

JavaScript não protege a propriedade hasOwnProperty; assim, se a possibilidade existe de um objeto poder ter uma propriedade com este nome, é necessário usar um hasOwnProperty externo para obter resultados corretos:

- -
var foo = {
-  hasOwnProperty: function() {
-    return false;
-  },
-  bar: 'Aqui os dragões'
-};
-
-foo.hasOwnProperty('bar'); // sempre retornará false
-
-// Use outro objeto hasOwnProperty e chame-o com 'this' definido como foo
-({}).hasOwnProperty.call(foo, 'bar'); // true
-
-// É também possível usar a propriedade hasOwnProperty através do protótipo do objeto para este propósito
-Object.prototype.hasOwnProperty.call(foo, 'bar'); // true
-
- -

Note que no último caso, não há objetos recém-criados.

- -

Especificações

- - - - - - - - - - - - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName('ES3')}}{{Spec2('ES3')}}Definição inicial. Implementado em JavaScript 1.5.
{{SpecName('ES5.1', '#sec-15.2.4.5', 'Object.prototype.hasOwnProperty')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-object.prototype.hasownproperty', 'Object.prototype.hasOwnProperty')}}{{Spec2('ES6')}} 
- -

Compatibilidade entre browsers

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
CaracterísticaAndroidChrome para AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Veja também

- - diff --git a/files/pt-pt/web/javascript/reference/global_objects/object/index.html b/files/pt-pt/web/javascript/reference/global_objects/object/index.html deleted file mode 100644 index e393f833b8..0000000000 --- a/files/pt-pt/web/javascript/reference/global_objects/object/index.html +++ /dev/null @@ -1,184 +0,0 @@ ---- -title: Object -slug: Web/JavaScript/Reference/Global_Objects/Object -tags: - - Constructor - - Construtor - - JavaScript - - Object - - Objeto -translation_of: Web/JavaScript/Reference/Global_Objects/Object ---- -
{{JSRef}}
- -

o construtor Object cria um wrapper de objeto.

- -

Sintaxe

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

Parâmetros

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

Descrição

- -

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

- -

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

- -

See also the object initializer / literal syntax.

- -

Propriedades de um construtor Object

- -
-
Object.length
-
Tem um valor de 1.
-
{{jsxref("Object.prototype")}}
-
Permite a adição de propriedades para todos os objetos do tipo Object.
-
- -

Métodos de um construtor Object

- -
-
{{jsxref("Object.assign()")}}
-
Copies the values of all enumerable own properties from one or more source objects to a target object.
-
{{jsxref("Object.create()")}}
-
Creates a new object with the specified prototype object and properties.
-
{{jsxref("Object.defineProperty()")}}
-
Adds the named property described by a given descriptor to an object.
-
{{jsxref("Object.defineProperties()")}}
-
Adds the named properties described by the given descriptors to an object.
-
{{jsxref("Object.entries()")}}
-
Returns an array containing all of the [key, value] pairs of a given object's own enumerable string properties.
-
{{jsxref("Object.freeze()")}}
-
Freezes an object: other code can't delete or change any properties.
-
{{jsxref("Object.fromEntries()")}}
-
Returns a new object from an iterable of key-value pairs (reverses {{jsxref("Object.entries")}}).
-
{{jsxref("Object.getOwnPropertyDescriptor()")}}
-
Returns a property descriptor for a named property on an object.
-
{{jsxref("Object.getOwnPropertyDescriptors()")}}
-
Returns an object containing all own property descriptors for an object.
-
{{jsxref("Object.getOwnPropertyNames()")}}
-
Returns an array containing the names of all of the given object's own enumerable and non-enumerable properties.
-
{{jsxref("Object.getOwnPropertySymbols()")}}
-
Returns an array of all symbol properties found directly upon a given object.
-
{{jsxref("Object.getPrototypeOf()")}}
-
Returns the prototype of the specified object.
-
{{jsxref("Object.is()")}}
-
Compares if two values are the same value. Equates all NaN values (which differs from both Abstract Equality Comparison and Strict Equality Comparison).
-
{{jsxref("Object.isExtensible()")}}
-
Determines if extending of an object is allowed.
-
{{jsxref("Object.isFrozen()")}}
-
Determines if an object was frozen.
-
{{jsxref("Object.isSealed()")}}
-
Determines if an object is sealed.
-
{{jsxref("Object.keys()")}}
-
Returns an array containing the names of all of the given object's own enumerable string properties.
-
{{jsxref("Object.preventExtensions()")}}
-
Prevents any extensions of an object.
-
{{jsxref("Object.seal()")}}
-
Prevents other code from deleting properties of an object.
-
{{jsxref("Object.setPrototypeOf()")}}
-
Sets the prototype (i.e., the internal [[Prototype]] property).
-
{{jsxref("Object.values()")}}
-
Returns an array containing the values that correspond to all of a given object's own enumerable string properties.
-
- -

Instâcias de Object e objeto protótipo Object

- -

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

- -

Propriedades

- -
{{page('//pt-PT/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype', 'Propriedades') }}
- -

Métodos

- -
{{page('//pt-PT/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype', 'Métodos') }}
- -

Deleting a property from an object

- -

There isn't any method in an Object itself to delete its own properties (e.g. like Map.prototype.delete()). To do so one has to use the delete operator.

- -

Exemplos

- -

Using Object given undefined and null types

- -

The following examples store an empty Object object in o:

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

Using Object to create Boolean objects

- -

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

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

Especificações

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.2', 'Object')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-object-objects', 'Object')}}{{Spec2('ES6')}}Added Object.assign, Object.getOwnPropertySymbols, Object.setPrototypeOf, Object.is
{{SpecName('ESDraft', '#sec-object-objects', 'Object')}}{{Spec2('ESDraft')}}Added Object.entries, Object.values and Object.getOwnPropertyDescriptors.
- -

Compatibilidade de navegador

- -
- - -

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

-
- -

See also

- - diff --git a/files/pt-pt/web/javascript/reference/global_objects/string/index.html b/files/pt-pt/web/javascript/reference/global_objects/string/index.html deleted file mode 100644 index 4ccc8f5f81..0000000000 --- a/files/pt-pt/web/javascript/reference/global_objects/string/index.html +++ /dev/null @@ -1,326 +0,0 @@ ---- -title: String -slug: Web/JavaScript/Reference/Global_Objects/String -tags: - - ECMAScript 2015 - - JavaScript - - Referencia - - String -translation_of: Web/JavaScript/Reference/Global_Objects/String ---- -
{{JSRef}}
- -

O objeto global String é um construtor de strings ou sequência de carateres.

- -

Sintaxe

- -

Os literais de string assumem as formas:

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

As Strings podem também ser criadas usando o objecto global string directamente:

- -
String(thing)
-new String(thing)
- -

Parâmetros

- -
-
thing
-
Qualquer parâmetro para ser convertido numa string.
-
- -

Strings modelo

- -

A partir de ECMAScript 2015, os literais de strings podem também ser chamados de Modelo strings:

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

Notação Escape

- -

Além dos carateres regulares e imprmiveis, os carateres especiais também podem ser codificados com notação escape:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
CódigoResultado
\XXX (XXX = 1 - 3 octal digits; range of 0 - 377)ISO-8859-1 character / Unicode code point between U+0000 and U+00FF
\'Aspas simples
\"Aspas duplas
\\Barra invertida
\nNova linha
\rcarriage return
\vTab vertical
\tTab
\bbackspace
\fform feed
\uXXXX (XXXX = 4 hex digits; range of 0x0000 - 0xFFFF)UTF-16 code unit / Unicode code point between U+0000 and U+FFFF
\u{X} ... \u{XXXXXX} (X…XXXXXX = 1 - 6 hex digits; range of 0x0 - 0x10FFFF)UTF-32 code unit / Unicode code point between U+0000 and U+10FFFF {{experimental_inline}}
\xXX (XX = 2 hex digits; range of 0x00 - 0xFF)ISO-8859-1 character / Unicode code point between U+0000 and U+00FF
- -
-

Note: Ao contrário de algumas outras linguagens, o Javascript não faz distinção entre strings com aspas simples e aspas duplas; Portanto a notação "escape" funciona em strings independente se foi utilizada aspas simples, ou aspas duplas na criação.

-
- -

Strings literais longas

- -

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

- -

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

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

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

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

Both of these result in identical strings being created.

- -

Descrição

- -

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

- -

Acesso de caráter

- -

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

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

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

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

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

- -

Comparação de strings

- -

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

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

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

- -

Distinção entre string primitivas e objetos String

- -

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

- -

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

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

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

- -
-

Nota: a == b compares the strings in a and b for being equal in the usual case-sensitive way. If you wish to compare without regard to upper or lower case characters, use a function similar to this:

- -

function isEqual(str1, str2)
-     {
-     return str1.toUpperCase()===str2.toUpperCase();
-     } // isEqual

- -

Upper case is used instead of lower case in this function due to problems with certain UTF-8 character conversions.

-
- -

Distinção entre string primitivas e objetos String

- -

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

- -

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

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

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

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

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

- -

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

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

Propriedades

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

Métodos

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

Instâncias de String

- -

Propriedades

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

Métodos

- -

Methods unrelated to HTML

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

HTML wrapper methods

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

Exemplos

- -

Conversão de String

- -

It's possible to use String as a more reliable {{jsxref("String.prototype.toString()", "toString()")}} alternative, as it works when used on {{jsxref("null")}}, {{jsxref("undefined")}}, and on {{jsxref("Symbol", "symbols")}}. For example:

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

Especificações

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName('ESDraft', '#sec-string-objects', 'String')}}{{Spec2('ESDraft')}}
{{SpecName('ES2015', '#sec-string-objects', 'String')}}{{Spec2('ES2015')}}
{{SpecName('ES5.1', '#sec-15.5', 'String')}}{{Spec2('ES5.1')}}
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition.
- -

Compatibilidade de navegador

- - - -

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

- -

Consulte também:

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

O método indexOf() retorna o indíce da primeira ocorrência do valor especificado no objeto {{jsxref("String")}}, começando a procura a partir de fromIndex. Retorna -1 se o valor não for encontrado.

- -

Sintaxe

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

Parâmetros

- -
-
searchValue
-
Uma string com o valor pelo qual se procura.
-
fromIndex {{optional_inline}}
-
O ponto da string a partir do qual a procura deverá começar. Pode ter o valor de um qualquer inteiro. O valor por predefinição é 0. Se o fromIndex < 0 a procura é feita em toda a string (o mesmo que passar o valor 0). Se fromIndex >= str.length, o método retornará -1, exceção feita quando o valor de searchValue é uma string vazia, nesse caso retorna str.length.
-
- -

Descrição

- -

Os caractéres numa string são indexadas da esquerda para a direita. O índice do primeira caractér é 0, e o índice do último caractér da string, chamado de stringName, é stringName.length - 1.

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

Case-sensitivity

- -

O método indexOf() é sensível a maiúsculas e minúsculas. Por exemplo, a seguinte expressão retorna -1:

- -
'Blue Whale'.indexOf('blue'); // retorna -1
-
- -

Verificando ocorrências

- -

Repara que '0' não é avaliado como true e '-1' não é avaliado como false. Sendo assim, a forma correta de verificar se uma string específica existe dentro de outra string deverá ser:

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

Exemplos

- -

Usando indexOf() e lastIndexOf()

- -

O seguinte exemplo usa indexOf() e {{jsxref("String.prototype.lastIndexOf()", "lastIndexOf()")}} para localizar valores na string "Brave new world".

- -
var anyString = 'Brave new world';
-
-console.log('O índice do primeiro w desde o início é ' + anyString.indexOf('w'));
-// imprime 8
-console.log('O índice do primeiro w desde o fim é ' + anyString.lastIndexOf('w'));
-// imprime 10
-
-console.log('O índice de "new" desde o início é ' + anyString.indexOf('new'));
-// imprime 6
-console.log('O índice de "new" desde o fim é ' + anyString.lastIndexOf('new'));
-// imprime 6
-
- -

indexOf() e sensibilidade a maiúsculas e minúsculas

- -

O seguinte exemplo define duas variáveis do tipo string. As variáveis contêm a mesma string exceto o facto da segunda string conter as todas as letras maiúsculas. O primeiro método {{domxref("console.log()")}} apresenta 19. Mas porque o método indexOf() é sensível a maiúsculas e minúsculas, a string "cheddar" não é encontrada em myCapString, logo o segundo método console.log() apresenta -1.

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

Usando indexOf() para contar as ocorrências de uma letra numa string

- -

O seguinte exemplo atribuí à variável count o número de ocorrências da letra 'e' na string str:

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

Especificações

- - - - - - - - - - - - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName('ES1')}}{{Spec2('ES1')}}Definição inicial.
{{SpecName('ES5.1', '#sec-15.5.4.7', 'String.prototype.indexOf')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-string.prototype.indexof', 'String.prototype.indexOf')}}{{Spec2('ES6')}} 
- -

Compatibilidade dos browsers

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FuncionalidadeChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FuncionalidadeAndroidChrome para AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Ver também

- - diff --git a/files/pt-pt/web/javascript/reference/global_objects/string/length/index.html b/files/pt-pt/web/javascript/reference/global_objects/string/length/index.html deleted file mode 100644 index 7774170252..0000000000 --- a/files/pt-pt/web/javascript/reference/global_objects/string/length/index.html +++ /dev/null @@ -1,125 +0,0 @@ ---- -title: String.length -slug: Web/JavaScript/Reference/Global_Objects/String/length -tags: - - JavaScript - - Property - - Prototype - - Reference - - String -translation_of: Web/JavaScript/Reference/Global_Objects/String/length ---- -
{{JSRef}}
- -

A propriedade length representa o comprimento de uma string.

- -

Sintaxe

- -
str.length
- -

Descrição

- -

Esta propriedade retorna o número de code units na string. {{interwiki("wikipedia", "UTF-16")}}, o formato usado pelo JavaScript para a string, usa um single 16-bit code unit para representar os caracteres mais comuns, mas necessita de usar two code units para os caracteres menos comuns, pelo que é possível que o valor retornado por length não seja igual ao número de caracteres numa string.

- -

Para uma string vazia, length is 0.

- -

A propriedade estática (static) String.length retorna o valor 1.

- -

Exemplos

- -

Uso simples

- -
var x = 'Mozilla';
-var empty = '';
-
-console.log('Mozilla tem de tamanho ' + x.length + ' code units');
-/* "Mozilla tem de tamanho 7 code units" */
-
-console.log('Uma string vazia tem tamanho ' + empty.length);
-/* "Uma string vazia tem tamanho 0" */
-
- -

Especificações

- - - - - - - - - - - - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName('ES1')}}{{Spec2('ES1')}}Definição inicial. Implementado em JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.5.5.1', 'String.prototype.length')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-properties-of-string-instances-length', 'String.prototype.length')}}{{Spec2('ES6')}} 
- -

Compatibilidade dos browsers

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FuncionalidadeChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FuncionalidadeAndroidChrome para AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Ver também

- - diff --git a/files/pt-pt/web/javascript/reference/global_objects/string/trim/index.html b/files/pt-pt/web/javascript/reference/global_objects/string/trim/index.html deleted file mode 100644 index 8ef29112f8..0000000000 --- a/files/pt-pt/web/javascript/reference/global_objects/string/trim/index.html +++ /dev/null @@ -1,139 +0,0 @@ ---- -title: String.prototype.trim() -slug: Web/JavaScript/Reference/Global_Objects/String/Trim -tags: - - ECMAScript 5 - - JavaScript - - Prototipo - - Referencia - - String - - metodo -translation_of: Web/JavaScript/Reference/Global_Objects/String/Trim ---- -
{{JSRef}}
- -

O método trim() elimina espaço em branco de ambos os extremos dum string. Espaço em branco neste contexto são todos os caracteres que apenas representam espaço (espaço, tabulação, espaço fixo, etc.) e todos os caracteres que representam limites de linha (LF, CR, etc.).

- -

Sintaxe

- -
str.trim()
- -

Valor devolvido

- -

Um novo string que representa o string que chamou despojado do espaço em branco de ambos os extremos.

- -

Descrição

- -

O método trim() devolve o string despojado do espaço em branco de ambos os extremos. trim() não afecta o valor do string em si.

- -

Exemplos

- -

Using trim()

- -

O exemplo que se segue mostra o string 'foo' em minúsculas:

- -
var orig = '   foo  ';
-console.log(orig.trim()); // 'foo'
-
-// Outro exemplo de .trim() eliminando espaço em branco de apenas um lado.
-
-var orig = 'foo    ';
-console.log(orig.trim()); // 'foo'
-
- -

Polyfill

- -

Ao correr o código que se segue antes de qualquer outro criará trim() se não estiver nativamente disponível.

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

Especificações

- - - - - - - - - - - - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName('ES5.1', '#sec-15.5.4.20', 'String.prototype.trim')}}{{Spec2('ES5.1')}}Definição inicial. Implementada em JavaScript 1.8.1.
{{SpecName('ES6', '#sec-string.prototype.trim', 'String.prototype.trim')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-string.prototype.trim', 'String.prototype.trim')}}{{Spec2('ESDraft')}} 
- -

Compatibilidade de navegadores

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.9.1")}}{{CompatIE("9")}}{{CompatOpera("10.5")}}{{CompatSafari("5")}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
CaracterísticaAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Ver também

- - diff --git a/files/pt-pt/web/javascript/reference/global_objects/symbol/hasinstance/index.html b/files/pt-pt/web/javascript/reference/global_objects/symbol/hasinstance/index.html deleted file mode 100644 index 3ba9666678..0000000000 --- a/files/pt-pt/web/javascript/reference/global_objects/symbol/hasinstance/index.html +++ /dev/null @@ -1,114 +0,0 @@ ---- -title: Symbol.hasInstance -slug: Web/JavaScript/Reference/Global_Objects/Symbol/hasInstance -tags: - - Propriedade - - Referencia -translation_of: Web/JavaScript/Reference/Global_Objects/Symbol/hasInstance ---- -
{{JSRef}}
- -

O symbol bem-conhecido Symbol.hasInstance é usado para determinar se um objecto construtor reconhece um objecto como de sua instância. O comportamento do operador {{jsxref("Operators/instanceof", "instanceof")}} pode ser customizado por este symbol.

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

Exemplos

- -

Tu podes implementar o comportamento customizado do seu instanceof deste jeito; por exemplo:

- -
class MyArray {
-  static [Symbol.hasInstance](instance) {
-    return this.prototype.isPrototypeOf(instance) ||
-           Array.isArray(instance);
-  }
-}
-
-console.log([] instanceof MyArray); // true
-console.log(new MyArray instanceof MyArray); // true
-console.log(new Image instanceof MyArray); // false
-
-class MySubArray extends MyArray {}
-console.log(new MySubArray instanceof MySubArray); // true
-console.log(new MySubArray instanceof MyArray); // true
-console.log(new MyArray instanceof MySubArray); // false
- -

Especificações

- - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES6', '#sec-symbol.hasinstance', 'Symbol.hasInstance')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-symbol.hasinstance', 'Symbol.hasInstance')}}{{Spec2('ESDraft')}} 
- -

Compatibilidade com os navegadores

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome(51)}}{{ CompatGeckoDesktop(50) }}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatUnknown}}{{ CompatGeckoMobile(50) }}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}
-
- -

Veja também

- - diff --git a/files/pt-pt/web/javascript/reference/global_objects/symbol/index.html b/files/pt-pt/web/javascript/reference/global_objects/symbol/index.html deleted file mode 100644 index 00148cd9b1..0000000000 --- a/files/pt-pt/web/javascript/reference/global_objects/symbol/index.html +++ /dev/null @@ -1,458 +0,0 @@ ---- -title: Symbol -slug: Web/JavaScript/Reference/Global_Objects/Symbol -tags: - - ECMAScript6 - - JavaScript - - NeedsTranslation - - Symbol - - TopicStub -translation_of: Web/JavaScript/Reference/Global_Objects/Symbol ---- -
{{JSRef}}
- -

A symbol is a unique and immutable data type. It may be used as an identifier for object properties. The Symbol object is an implicit object wrapper for the symbol {{Glossary("Primitive", "primitive data type")}}.

- -

Syntax

- -
Symbol([description])
- -

Parameters

- -
-
description {{optional_inline}}
-
Optional, string. A description of the symbol which can be used for debugging but not to access the symbol itself.
-
- -

Description

- -

To create a new primitive symbol, you write Symbol() with an optional string as its description:

- -
var sym1 = Symbol();
-var sym2 = Symbol("foo");
-var sym3 = Symbol("foo");
-
- -

The above code creates three new symbols. Note that Symbol("foo") does not coerce the string "foo" into a symbol. It creates a new symbol each time:

- -
Symbol("foo") === Symbol("foo"); // false
- -

The following syntax with the {{jsxref("Operators/new", "new")}} operator will throw a {{jsxref("TypeError")}}:

- -
var sym = new Symbol(); // TypeError
- -

This prevents authors from creating an explicit Symbol wrapper object instead of a new symbol value and might be surprising as creating explicit wrapper objects around primitive data types is generally possible (for example, new Boolean, new String and new Number).

- -

If you really want to create a Symbol wrapper object, you can use the Object() function:

- -
var sym = Symbol("foo");
-typeof sym;     // "symbol"
-var symObj = Object(sym);
-typeof symObj;  // "object"
-
- -

Shared symbols in the global symbol registry

- -

The above syntax using the Symbol() function will not create a global symbol that is available in your whole codebase. To create symbols available across files and even across realms (each of which has its own global scope), use the methods {{jsxref("Symbol.for()")}} and {{jsxref("Symbol.keyFor()")}} to set and retrieve symbols from the global symbol registry.

- -

Finding symbol properties on objects

- -

The method {{jsxref("Object.getOwnPropertySymbols()")}} returns an array of symbols and lets you find symbol properties on a given object. Note that every object is initialized with no own symbol properties, so that this array will be empty unless you've set symbol properties on the object.

- -

Properties

- -
-
Symbol.length
-
Length property whose value is 0.
-
{{jsxref("Symbol.prototype")}}
-
Represents the prototype for the Symbol constructor.
-
- -

Well-known symbols

- -

In addition to your own symbols, JavaScript has some built-in symbols which represent internal language behaviors which were not exposed to developers in ECMAScript 5 and before. These symbols can be accessed using the following properties:

- -

Iteration symbols

- -
-
{{jsxref("Symbol.iterator")}}
-
A method returning the default iterator for an object. Used by for...of.
-
- -

Regular expression symbols

- -
-
{{jsxref("Symbol.match")}}
-
A method that matches against a string, also used to determine if an object may be used as a regular expression. Used by {{jsxref("String.prototype.match()")}}.
-
{{jsxref("Symbol.replace")}}
-
A method that replaces matched substrings of a string. Used by {{jsxref("String.prototype.replace()")}}.
-
{{jsxref("Symbol.search")}}
-
A method that returns the index within a string that matches the regular expression. Used by {{jsxref("String.prototype.search()")}}.
-
{{jsxref("Symbol.split")}}
-
A method that splits a string at the indices that match a regular expression. Used by {{jsxref("String.prototype.split()")}}.
-
- -

Other symbols

- -
-
{{jsxref("Symbol.hasInstance")}}
-
A method determining if a constructor object recognizes an object as its instance. Used by {{jsxref("Operators/instanceof", "instanceof")}}.
-
{{jsxref("Symbol.isConcatSpreadable")}}
-
A Boolean value indicating if an object should be flattened to its array elements. Used by {{jsxref("Array.prototype.concat()")}}.
-
{{jsxref("Symbol.unscopables")}}
-
An object value of whose own and inherited property names are excluded from the with environment bindings of the associated object.
-
{{jsxref("Symbol.species")}}
-
A constructor function that is used to create derived objects.
-
{{jsxref("Symbol.toPrimitive")}}
-
A method converting an object to a primitive value.
-
{{jsxref("Symbol.toStringTag")}}
-
A string value used for the default description of an object. Used by {{jsxref("Object.prototype.toString()")}}.
-
- -

Methods

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

Symbol prototype

- -

All Symbols inherit from {{jsxref("Symbol.prototype")}}.

- -

Properties

- -

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

- -

Methods

- -

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

- -

Examples

- -

Using the typeof operator with symbols

- -

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

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

Symbol type conversions

- -

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

- - - -

Symbols and for...in iteration

- -

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

- -
var obj = {};
-
-obj[Symbol("a")] = "a";
-obj[Symbol.for("b")] = "b";
-obj["c"] = "c";
-obj.d = "d";
-
-for (var i in obj) {
-   console.log(i); // logs "c" and "d"
-}
- -

Symbols and JSON.stringify()

- -

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

- -
JSON.stringify({[Symbol("foo")]: "foo"});
-// '{}'
- -

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

- -

Symbol wrapper objects as property keys

- -

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

- -
var sym = Symbol("foo");
-var obj = {[sym]: 1};
-obj[sym];            // 1
-obj[Object(sym)];    // still 1
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES6', '#sec-symbol-objects', 'Symbol')}}{{Spec2('ES6')}}Initial definition
{{SpecName('ESDraft', '#sec-symbol-objects', 'Symbol')}}{{Spec2('ESDraft')}} 
- -

Browser compatibility

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome(38)}}{{CompatGeckoDesktop(36)}}{{CompatNo}}259
Symbol.iterator (@@iterator){{CompatChrome(38)}}{{CompatGeckoDesktop(36)}}{{CompatNo}}259
Symbol.unscopables (@@unscopables){{CompatChrome(38)}}{{CompatGeckoDesktop(48)}}{{CompatNo}}259
Symbol.match (@@match){{CompatChrome(50)}}{{CompatGeckoDesktop(40)}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}
Symbol.species (@@species){{CompatChrome(51)}}{{CompatGeckoDesktop(41)}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}
Symbol.toPrimitive (@@toPrimitive){{CompatChrome(48)}}{{CompatGeckoDesktop(44)}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}
Symbol.replace (@@replace){{CompatChrome(50)}}{{CompatGeckoDesktop(48)}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}
Symbol.search (@@search){{CompatChrome(50)}}{{CompatGeckoDesktop(48)}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}
Symbol.split (@@split){{CompatChrome(50)}}{{CompatGeckoDesktop(48)}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}
Symbol.isConcatSpreadable (@@isconcatspreadable){{CompatChrome(48)}}{{CompatGeckoDesktop(48)}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}
Symbol.hasInstance (@@hasInstance){{CompatChrome(51)}}{{CompatGeckoDesktop(50)}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}
Symbol.toStringTag (@@toStringTag){{CompatChrome(49)}}{{CompatGeckoDesktop(51)}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatChrome(38)}}{{CompatGeckoMobile(36)}}{{CompatNo}}259
Symbol.iterator (@@iterator){{CompatUnknown}}{{CompatChrome(38)}}{{CompatGeckoMobile(36)}}{{CompatNo}}259
Symbol.unscopables (@@unscopables){{CompatUnknown}}{{CompatChrome(38)}}{{CompatGeckoMobile(48)}}{{CompatNo}}259
Symbol.match (@@match){{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile(40)}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}
Symbol.species (@@species){{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile(41)}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}
Symbol.toPrimitive (@@toPrimitive){{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile(44)}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}
Symbol.replace (@@replace){{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile(48)}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}
Symbol.search (@@search){{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile(48)}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}
Symbol.split (@@split){{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile(48)}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}
Symbol.isConcatSpreadable (@@isconcatspreadable){{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile(48)}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}
Symbol.hasInstance (@@hasInstance){{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile(50)}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}
Symbol.toStringTag (@@toStringTag){{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile(51)}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}
-
- -

See also

- - diff --git a/files/pt-pt/web/javascript/reference/index.html b/files/pt-pt/web/javascript/reference/index.html deleted file mode 100644 index aa2f94e880..0000000000 --- a/files/pt-pt/web/javascript/reference/index.html +++ /dev/null @@ -1,307 +0,0 @@ ---- -title: Referência de JavaScript -slug: Web/JavaScript/Reference -tags: - - ECMAScript6 - - ES6 - - 'I10n:priority' - - JS - - JavaScript - - Programação - - Página Landing - - Referencia - - es -translation_of: Web/JavaScript/Reference ---- -
{{JsSidebar}}
- -

Esta parte da secção de JavaScript na MDN serve como um repositório de factos sobre a linguage JavaScript. Leia mais sobre esta referência.

- -

Integrações

- -

Objetos integrados padrões de JavaScript, em conjunto com os seus métodos e propriedades.

- - - - - - - - - -

Declações (Statements)

- -

Declarações e instruções de JavaScript

- - - - - -

Expressões e operadores

- -

Expressões e operadores de JavaScript

- -
- - - - - -
- -

Funções

- -

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

- - - -

Páginas adicionais de referência

- - diff --git a/files/pt-pt/web/javascript/reference/operators/comma_operator/index.html b/files/pt-pt/web/javascript/reference/operators/comma_operator/index.html deleted file mode 100644 index fd3d1ab53c..0000000000 --- a/files/pt-pt/web/javascript/reference/operators/comma_operator/index.html +++ /dev/null @@ -1,95 +0,0 @@ ---- -title: Operador Vírgula -slug: Web/JavaScript/Reference/Operators/Comma_Operator -tags: - - Composto - - Expressão - - Funcionalidade de Linguagem - - JavaScript - - Operador - - Referencia - - Vírgula -translation_of: Web/JavaScript/Reference/Operators/Comma_Operator -original_slug: Web/JavaScript/Reference/Operadores/Operador_virgula ---- -
Operador {{jsSidebar("Operators")}}
- -

operador vírgula (,) avalia cada um dos seus operandos (da esquerda para a direita) e devolve o valor do último operando. This lets you create a compound expression in which multiple expressions are evaluated, with the compound expression's final value being the value of the rightmost of its member expressions. This is commonly used to provide multiple parameters to a for loop.

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

Sintaxe

- -
expr1, expr2, expr3...
- -

Parâmetros

- -
-
expr1, expr2, expr3...
-
One or more expressions, the last of which is returned as the value of the compound expression.
-
- -

Notas de utilização

- -

You can use the comma operator when you want to include multiple expressions in a location that requires a single expression. The most common usage of this operator is to supply multiple parameters in a for loop.

- -

The comma operator is fully different from the comma within arrays, objects, and function arguments and parameters.

- -

Exemplos

- -

If a is a 2-dimensional array with 10 elements on each side, the following code uses the comma operator to increment i and decrement j at once.

- -

The following code prints the values of the diagonal elements in the array:

- -
for (var i = 0, j = 9; i <= 9; i++, j--)
-  console.log('a[' + i + '][' + j + '] = ' + a[i][j]);
- -

Note that the comma operators in assignments may appear not to have the normal effect of comma operators because they don't exist within an expression. In the following example, a is set to the value of b = 3 (which is 3), but the c = 4 expression still evaluates and its result returned to console (i.e., 4). This is due to operator precedence and associativity.

- -
var a, b, c;
-
-a = b = 3, c = 4; // Returns 4 in console
-console.log(a); // 3 (left-most)
-
-var x, y, z;
-
-x = (y = 5, z = 6); // Returns 6 in console
-console.log(x); // 6 (right-most)
-
- -

Processing and then returning

- -

Another example that one could make with comma operator is processing before returning. As stated, only the last element will be returned but all others are going to be evaluated as well. So, one could do:

- -
function myFunc() {
-  var x = 0;
-
-  return (x += 1, x); // the same as return ++x;
-}
- -

Especificações

- - - - - - - - - - -
Especificação
{{SpecName('ESDraft', '#sec-comma-operator', 'Comma operator')}}
- -

Compatibilidade de navegador

- - - -

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

- -

Consulte também

- - diff --git a/files/pt-pt/web/javascript/reference/operators/function/index.html b/files/pt-pt/web/javascript/reference/operators/function/index.html deleted file mode 100644 index fe2858c796..0000000000 --- a/files/pt-pt/web/javascript/reference/operators/function/index.html +++ /dev/null @@ -1,140 +0,0 @@ ---- -title: Expressão função (Function expression) -slug: Web/JavaScript/Reference/Operators/function -tags: - - Expressões Primárias - - Funiconaldiade de Linguagem - - Função - - JavaScript - - Operador -translation_of: Web/JavaScript/Reference/Operators/function -original_slug: Web/JavaScript/Reference/Operadores/função ---- -
{{jsSidebar("Operators")}}
- -

A palavra-chave function  pode ser utilziada para definir uma função dentro de uma expressão.

- -

You can also define functions using the Function constructor and a function declaration.

- -
{{EmbedInteractiveExample("pages/js/expressions-functionexpression.html", "shorter")}}
- - - -

Sintaxe

- -
let myFunction = function [name]([param1[, param2[, ..., paramN]]]) {
-   statements
-};
- -

As of ES2015, you can also use {{jsxref("Functions/Arrow_functions", "arrow functions")}}.

- -

Parâmetros

- -
-
name {{optional_inline}}
-
The function name. Can be omitted, in which case the function is anonymous. The name is only local to the function body.
-
paramN {{optional_inline}}
-
The name of an argument to be passed to the function.
-
statements {{optional_inline}}
-
The statements which comprise the body of the function.
-
- -

Descrição

- -

A function expression is very similar to and has almost the same syntax as a function declaration (see {{jsxref("Statements/function", "function statement")}} for details). The main difference between a function expression and a function declaration is the function name, which can be omitted in function expressions to create anonymous functions. A function expression can be used as an IIFE (Immediately Invoked Function Expression) which runs as soon as it is defined. See also the chapter about {{jsxref("Functions", "functions")}} for more information.

- -

Function expression hoisting

- -

Function expressions in JavaScript are not hoisted, unlike {{jsxref("Statements/function", "function declarations", "#Function_declaration_hoisting")}}. You can't use function expressions before you define them:

- -
console.log(notHoisted) // undefined
-//  even though the variable name is hoisted, the definition isn't. so it's undefined.
-notHoisted(); // TypeError: notHoisted is not a function
-
-var notHoisted = function() {
-   console.log('bar');
-};
-
- -

Named function expression

- -

If you want to refer to the current function inside the function body, you need to create a named function expression. This name is then local only to the function body (scope). This also avoids using the non-standard {{jsxref("Functions/arguments/callee", "arguments.callee")}} property.

- -
let math = {
-  'factit': function factorial(n) {
-    console.log(n)
-    if (n <= 1) {
-      return 1;
-    }
-    return n * factorial(n - 1);
-  }
-};
-
-math.factit(3) //3;2;1;
-
- -

The variable the function expression is assigned to will have a name property. The name doesn't change if it's assigned to a different variable. If function name is omitted, it will be the variable name (implicit name). If function name is present, it will be the function name (explicit name). This also applies to {{jsxref("Functions/Arrow_functions", "arrow functions")}} (arrows don't have a name so you can only give the variable an implicit name).

- -
var foo = function() {}
-foo.name // "foo"
-
-var foo2 = foo
-foo2.name // "foo"
-
-var bar = function baz() {}
-bar.name // "baz"
-
-console.log(foo === foo2); // true
-console.log(typeof baz); // undefined
-console.log(bar === baz); // false (errors because baz == undefined)
-
- -

Exemplos

- -

The following example defines an unnamed function and assigns it to x. The function returns the square of its argument:

- -
var x = function(y) {
-   return y * y;
-};
-
- -

More commonly it is used as a callback:

- -
button.addEventListener('click', function(event) {
-    console.log('button is clicked!')
-})
- -

Especificações

- - - - - - - - - - - - -
Especificação
{{SpecName('ESDraft', '#sec-function-definitions', 'Function definitions')}}
- -

Compatibilidade de navegador

- - - -

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

- -

Consulte também 

- - diff --git a/files/pt-pt/web/javascript/reference/operators/index.html b/files/pt-pt/web/javascript/reference/operators/index.html deleted file mode 100644 index 2856a917bc..0000000000 --- a/files/pt-pt/web/javascript/reference/operators/index.html +++ /dev/null @@ -1,310 +0,0 @@ ---- -title: Expressões e operadores -slug: Web/JavaScript/Reference/Operators -tags: - - JavaScript - - Operadores - - Página Landing - - Resumo - - Sinopse -translation_of: Web/JavaScript/Reference/Operators -original_slug: Web/JavaScript/Reference/Operadores ---- -
{{jsSidebar("Operators")}}
- -

Este capítulo documenta todos os operadores, expressões e palavras-chave da linguagem JavaScript.

- -

Expressões e operadores por categoria

- -

For an alphabetical listing see the sidebar on the left.

- -

Expressões primárias

- -

Basic keywords and general expressions in JavaScript.

- -
-
{{JSxRef("Operators/this", "this")}}
-
The this keyword refers to a special property of an execution context.
-
{{JSxRef("Operators/function", "function")}}
-
The function keyword defines a function expression.
-
{{JSxRef("Operators/class", "class")}}
-
The class keyword defines a class expression.
-
{{JSxRef("Operators/function*", "function*")}}
-
The function* keyword defines a generator function expression.
-
{{JSxRef("Operators/yield", "yield")}}
-
Pause and resume a generator function.
-
{{JSxRef("Operators/yield*", "yield*")}}
-
Delegate to another generator function or iterable object.
-
{{JSxRef("Operators/async_function", "async function")}}
-
The async function defines an async function expression.
-
{{JSxRef("Operators/await", "await")}}
-
Pause and resume an async function and wait for the promise's resolution/rejection.
-
{{JSxRef("Global_Objects/Array", "[]")}}
-
Array initializer/literal syntax.
-
{{JSxRef("Operators/Object_initializer", "{}")}}
-
Object initializer/literal syntax.
-
{{JSxRef("Global_Objects/RegExp", "/ab+c/i")}}
-
Regular expression literal syntax.
-
{{JSxRef("Operators/Grouping", "( )")}}
-
Grouping operator.
-
- -

Expressões "Left-hand-side"

- -

Left values are the destination of an assignment.

- -
-
{{jsxref("Operators/Property_accessors", "Property accessors", "", 1)}}
-
Member operators provide access to a property or method of an object
- (object.property and object["property"]).
-
{{jsxref("Operators/new", "new")}}
-
The new operator creates an instance of a constructor.
-
new.target
-
In constructors, new.target refers to the constructor that was invoked by {{jsxref("Operators/new", "new")}}.
-
{{jsxref("Operators/super", "super")}}
-
The super keyword calls the parent constructor.
-
{{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.
-
- -

Aumento e diminuição

- -

Postfix/prefix increment and postfix/prefix decrement operators.

- -
-
{{jsxref("Operators/Arithmetic_Operators", "A++", "#Increment")}}
-
Postfix increment operator.
-
{{jsxref("Operators/Arithmetic_Operators", "A--", "#Decrement")}}
-
Postfix decrement operator.
-
{{jsxref("Operators/Arithmetic_Operators", "++A", "#Increment")}}
-
Prefix increment operator.
-
{{jsxref("Operators/Arithmetic_Operators", "--A", "#Decrement")}}
-
Prefix decrement operator.
-
- -

Operadores unários

- -

A unary operation is operation with only one operand.

- -
-
{{jsxref("Operators/delete", "delete")}}
-
The delete operator deletes a property from an object.
-
{{jsxref("Operators/void", "void")}}
-
The void operator discards an expression's return value.
-
{{jsxref("Operators/typeof", "typeof")}}
-
The typeof operator determines the type of a given object.
-
{{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.
-
- -

Operadores de aritmética

- -

Arithmetic operators take numerical values (either literals or variables) as their operands and return a single numerical value.

- -
-
{{jsxref("Operators/Arithmetic_Operators", "+", "#Addition")}}
-
Addition operator.
-
{{jsxref("Operators/Arithmetic_Operators", "-", "#Subtraction")}}
-
Subtraction operator.
-
{{jsxref("Operators/Arithmetic_Operators", "/", "#Division")}}
-
Division operator.
-
{{jsxref("Operators/Arithmetic_Operators", "*", "#Multiplication")}}
-
Multiplication operator.
-
{{jsxref("Operators/Arithmetic_Operators", "%", "#Remainder")}}
-
Remainder operator.
-
- -
-
{{JSxRef("Operators/Arithmetic_Operators", "**", "#Exponentiation")}}
-
Exponentiation operator.
-
- -

Operadores relacionais

- -

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

Nota: => não é um operador, mas a notação para funções seta (arrow).

-
- -

Operadores de equality

- -

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

Operadores de binário bitwise

- -

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

Operadores de binário logical

- -

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

Operdor condicional (ternário)

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

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

-
-
- -

Operadores de Assignment

- -

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.

-
-
- -

Operador de aspas

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

Funcionalidades não padrão

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

Especificações

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{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')}}
- -

Compatibilidade de navegador

- - - -

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

- -

Consulte também

- - diff --git a/files/pt-pt/web/javascript/reference/operators/operator_precedence/index.html b/files/pt-pt/web/javascript/reference/operators/operator_precedence/index.html deleted file mode 100644 index a33ba19b4b..0000000000 --- a/files/pt-pt/web/javascript/reference/operators/operator_precedence/index.html +++ /dev/null @@ -1,462 +0,0 @@ ---- -title: Precedência de operador -slug: Web/JavaScript/Reference/Operators/Operator_Precedence -tags: - - Guía - - JavaScript - - precedência -translation_of: Web/JavaScript/Reference/Operators/Operator_Precedence -original_slug: Web/JavaScript/Reference/Operadores/Precedencia_operador ---- -
{{jsSidebar("Operators")}}
- -

A precedência de operador determina a maneira pela qual os operadores são analisados ​​em relação a cada um. Os operadores com maior precedência tornam-se operandos dos operadores com menor precedência..

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

Precedência e Associabilidade

- -

Consider an expression describable by the representation below. Note that both OP1 and OPare fill-in-the-blanks for OPerators.

- -
a OP b OP c
-
- -

If OP1 and OP2 have different precedence levels (see the table below), the operator with the highest precedence goes first and associativity does not matter. Observe how multiplication has higher associativity than addition and executed first, even though addition is written first in the code.

- -
console.log(3 + 10 * 2);   // logs 23
-console.log(3 + (10 * 2)); // logs 23 because parentheses here are superfluous
-console.log((3 + 10) * 2); // logs 26 because the parentheses change the order 
- -

Left-associativity (left-to-right) means that it is processed as (a OP1 b) OP2 c, while right-associativity (right-to-left) means it is interpreted as a OP1 (b OP2 c). Assignment operators are right-associative, so you can write:

- -
a = b = 5; // same as writing a = (b = 5);
-
- -

with the expected result that a and b get the value 5. This is because the assignment operator returns the value that is assigned. First, b is set to 5. Then the a is also set to 5, the return value of b = 5, aka right operand of the assignment.

- -

As another example, the unique exponentiation operator has right-associativity, whereas other arithmetic operators have left-associativity. It is interesting to note that, the order of evaluation is always left-to-right irregardless of associativity.

- - - - - - - - - - - - - - - - -
CódigoResultado
-
-function echo(name, num) {
-    console.log("Evaluating the " + name + " side");
-    return num;
-}
-// Notice the division operator (/)
-console.log(echo("left", 6) / echo("right", 2));
-
-
-
-Evaluating the left side
-Evaluating the right side
-3
-
-
-
-function echo(name, num) {
-    console.log("Evaluating the " + name + " side");
-    return num;
-}
-// Notice the exponentiation operator (**)
-console.log(echo("left", 2) ** echo("right", 3));
-
-
-Evaluating the left side
-Evaluating the right side
-8
-
- -

The difference in associativity comes into play when there are multiple operators of the same precedence. With only one operator or operators of different precedences, associativity does affect the output, as seen in the example above. In the example below, observe how associativity affects the output when multiple of the same operator are used.

- - - - - - - - - - - - - - - - - - - - -
CódigoResultado
-
-function echo(name, num) {
-    console.log("Evaluating the " + name + " side");
-    return num;
-}
-// Notice the division operator (/)
-console.log(echo("left", 6) / echo("middle", 2) / echo("right", 3));
-
-
-
-Evaluating the left side
-Evaluating the middle side
-Evaluating the right side
-1
-
-
-
-function echo(name, num) {
-    console.log("Evaluating the " + name + " side");
-    return num;
-}
-// Notice the exponentiation operator (**)
-console.log(echo("left", 2) ** echo("middle", 3) ** echo("right", 2));
-
-
-
-Evaluating the left side
-Evaluating the middle side
-Evaluating the right side
-512
-
-
-
-function echo(name, num) {
-    console.log("Evaluating the " + name + " side");
-    return num;
-}
-// Notice the parentheses around the left and middle exponentiation
-console.log((echo("left", 2) ** echo("middle", 3)) ** echo("right", 2));
-
-
-Evaluating the left side
-Evaluating the middle side
-Evaluating the right side
-64
-
- -

Looking at the code snippets above, 6 / 3 / 2 is the same as (6 / 3) / 2 because division is left-associative. Exponentiation, on the other hand, is right-associative, so 2 ** 3 ** 2 is the same as 2 ** (3 ** 2). Thus, doing (2 ** 3) ** 2 changes the order and results in the 64 seen in the table above.

- -

Remember that precedence comes before associativity. So, mixing division and exponentiation, the exponentiation comes before the division. For example, 2 ** 3 / 3 ** 2 results in 0.8888888888888888 because it is the same as (2 ** 3) / (3 ** 2).

- -

Note on Grouping and Short-Circuiting

- -

In the table below, Grouping is listed as having the highest precedence. However, that does not always mean the expression within the grouping symbols ( … ) is evaluated first, especially when it comes to short-circuiting.

- -

Short-circuiting is jargon for conditional evaluation. For example, in the expression a && (b + c), if a is “falsy”, then the sub-expression (b + c) will not even get evaluated, even if it is in parentheses. We could say that the logical disjunction operator (“OR”) is “short-circuited”. Along with logical disjunction, other short-circuited operators include logical conjunction (“AND”), nullish-coalescing, optional chaining, and the conditional operator. Some more examples follow.

- -
a || (b * c);  // evaluate `a` first, then produce `a` if `a` is “truthy”
-a && (b < c);  // evaluate `a` first, then produce `a` if `a` is “falsy”
-a ?? (b || c); // evaluate `a` first, then produce `a` if `a` is not `null` and not `undefined`
-a?.b.c;        // evaluate `a` first, then produce `a` if `a` is `null` or `undefined`
-
- -

Exemplos

- -
3 > 2 && 2 > 1
-// returns true
-
-3 > 2 > 1
-// Returns false because 3 > 2 is true, then true is converted to 1 in inequality operators, therefore true > 1 becomes 1 > 1, which
-//  is false. Adding parentheses makes things clear: (3 > 2) > 1.
-
-
- -

Tabela

- -

The following table is ordered from highest (20) to lowest (1) precedence.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
PrecedênciaTipo de operador (Operator)AssociatividadeOperadores individuais
20{{jsxref("Operators/Grouping", "Grouping")}}n/a( … )
19{{jsxref("Operators/Property_Accessors", "Member Access", "#Dot_notation")}}left-to-right… . …
{{jsxref("Operators/Property_Accessors", "Computed Member Access","#Bracket_notation")}}left-to-right… [ … ]
{{jsxref("Operators/new","new")}} (with argument list)n/anew … ( … )
Function Callleft-to-right… ( … )
18{{jsxref("Operators/new","new")}} (without argument list)right-to-leftnew …
17{{jsxref("Operators/Arithmetic_Operators","Postfix Increment","#Increment")}}n/a… ++
{{jsxref("Operators/Arithmetic_Operators","Postfix Decrement","#Decrement")}}… --
16Logical NOTright-to-left! …
Bitwise NOT~ …
Unary Plus+ …
Unary Negation- …
Prefix Increment++ …
Prefix Decrement-- …
typeoftypeof …
voidvoid …
deletedelete …
awaitawait …
15Exponentiationright-to-left… ** …
14Multiplicationleft-to-right… * …
Division… / …
Remainder… % …
13Additionleft-to-right… + …
Subtraction… - …
12Bitwise Left Shiftleft-to-right… << …
Bitwise Right Shift… >> …
Bitwise Unsigned Right Shift… >>> …
11Less Thanleft-to-right… < …
Less Than Or Equal… <= …
Greater Than… > …
Greater Than Or Equal… >= …
in… in …
instanceof… instanceof …
10Equalityleft-to-right… == …
Inequality… != …
Strict Equality… === …
Strict Inequality… !== …
9Bitwise ANDleft-to-right… & …
8Bitwise XORleft-to-right… ^ …
7Bitwise ORleft-to-right… | …
6Logical ANDleft-to-right… && …
5Logical ORleft-to-right… || …
4Conditionalright-to-left… ? … : …
3Assignmentright-to-left… = …
… += …
… -= …
… **= …
… *= …
… /= …
… %= …
… <<= …
… >>= …
… >>>= …
… &= …
… ^= …
… |= …
2{{jsxref("Operators/yield", "yield")}}right-to-leftyield …
{{jsxref("Operators/yield*", "yield*")}}yield* …
1Vírgula / Sequêncialeft-to-right… , …
diff --git a/files/pt-pt/web/javascript/reference/statements/block/index.html b/files/pt-pt/web/javascript/reference/statements/block/index.html deleted file mode 100644 index 4a6507702f..0000000000 --- a/files/pt-pt/web/javascript/reference/statements/block/index.html +++ /dev/null @@ -1,117 +0,0 @@ ---- -title: Bloco (block) -slug: Web/JavaScript/Reference/Statements/block -tags: - - Declaração - - Funcionalidade de Linguagem - - JavaScript - - Referencia -translation_of: Web/JavaScript/Reference/Statements/block -original_slug: Web/JavaScript/Reference/Extratos_e_declarações/bloco ---- -
Bloco {{jsSidebar("Statements")}}
- -

Uma declaralção bloco (ou declaração composto em outras linguagens) é utilizada para agrupar zero ou mais declarações. O bloco é delimitado por um par de chavetas (“chavetas { }”) e opcionalmente poderá ser {{jsxref("Statements/label", "labelled", "", 1)}}:

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

Sintaxe

- -

Declaração de Bloco

- -
{
-  StatementList
-}
-
- -

Declaração de Bloco Etiquetado

- -
LabelIdentifier: {
-  StatementList
-}
-
- -
-
StatementList
-
Statements grouped within the block statement.
-
LabelIdentifier
-
An optional {{jsxref("Statements/label", "label", "", 1)}} for visual identification or as a target for {{jsxref("Statements/break", "break")}}.
-
- -

Descrição

- -

The block statement is often called compound statement in other languages. It allows you to use multiple statements where JavaScript expects only one statement. Combining statements into blocks is a common practice in JavaScript. The opposite behavior is possible using an empty statement, where you provide no statement, although one is required.

- -

Blocks are commonly used in association with {{jsxref("Statements/if...else", "if...else")}} and {{jsxref("Statements/for", "for")}} statements.

- -

Block Scoping Rules

- -

With var or function declaration in non-strict mode

- -

Variables declared with var or created by function declarations in non-strict mode do not have block scope. Variables introduced within a block are scoped to the containing function or script, and the effects of setting them persist beyond the block itself. In other words, block statements do not introduce a scope. For example:

- -
var x = 1;
-{
-  var x = 2;
-}
-console.log(x); // logs 2
-
- -

This logs 2 because the var x statement within the block is in the same scope as the var x statement before the block.

- -

In non-strict code, function declarations inside blocks behave strangely. Do not use them.

- -

With let, const or function declaration in strict mode

- -

By contrast, identifiers declared with {{jsxref("Statements/let", "let")}} and {{jsxref("Statements/const", "const")}} do have block scope:

- -
let x = 1;
-{
-  let x = 2;
-}
-console.log(x); // logs 1
- -

The x = 2 is limited in scope to the block in which it was defined.

- -

The same is true of const:

- -
const c = 1;
-{
-  const c = 2;
-}
-console.log(c); // logs 1 and does not throw SyntaxError...
- -

Note that the block-scoped const c = 2 does not throw a SyntaxError: Identifier 'c' has already been declared because it can be declared uniquely within the block.

- -

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

- -

Especificações

- - - - - - - - - - - - -
Especificação
{{SpecName('ESDraft', '#sec-block', 'Block statement')}}
- -

Compatibilidade de navegador

- - - -

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

- -

Consulte também

- - diff --git a/files/pt-pt/web/javascript/reference/statements/for/index.html b/files/pt-pt/web/javascript/reference/statements/for/index.html deleted file mode 100644 index 687cd23cdc..0000000000 --- a/files/pt-pt/web/javascript/reference/statements/for/index.html +++ /dev/null @@ -1,146 +0,0 @@ ---- -title: for -slug: Web/JavaScript/Reference/Statements/for -tags: - - Declaração - - Funcionalidade de Linguagem - - JavaScript - - Loop - - Referencia - - Repetição - - for -translation_of: Web/JavaScript/Reference/Statements/for -original_slug: Web/JavaScript/Reference/Extratos_e_declarações/for ---- -
{{jsSidebar("Statements")}}
- -

A declaração "for" cria uma repetição (loop) que consiste de três expressões opcionais, entre parênteses e separados por ponto e vírgula, seguido de uma declaração (normalmente bdeclaraçãod e bloco (block)) para ser executada na repetição.

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

Sintaxe

- -
for ([initialization]; [condition]; [final-expression])
-   statement
- -
-
initialization
-
An expression (including assignment expressions) or variable declaration evaluated once before the loop begins. Typically used to initialize a counter variable. This expression may optionally declare new variables with var or let keywords. Variables declared with var are not local to the loop, i.e. they are in the same scope the for loop is in. Variables declared with let are local to the statement.
-
The result of this expression is discarded.
-
condition
-
An expression to be evaluated before each loop iteration. If this expression evaluates to true, statement is executed. This conditional test is optional. If omitted, the condition always evaluates to true. If the expression evaluates to false, execution skips to the first expression following the for construct.
-
final-expression
-
An expression to be evaluated at the end of each loop iteration. This occurs before the next evaluation of condition. Generally used to update or increment the counter variable.
-
statement
-
A statement that is executed as long as the condition evaluates to true. To execute multiple statements within the loop, use a {{jsxref("Statements/block", "block", "", 0)}} statement ({ ... }) to group those statements. To execute no statement within the loop, use an {{jsxref("Statements/empty", "empty", "", 0)}} statement (;).
-
- -

Exemplos

- -

Using for

- -

The following for statement starts by declaring the variable i and initializing it to 0. It checks that i is less than nine, performs the two succeeding statements, and increments i by 1 after each pass through the loop.

- -
for (let i = 0; i < 9; i++) {
-   console.log(i);
-   // more statements
-}
-
- -

Optional for expressions

- -

All three expressions in the head of the for loop are optional.

- -

For example, in the initialization block it is not required to initialize variables:

- -
var i = 0;
-for (; i < 9; i++) {
-    console.log(i);
-    // more statements
-}
-
- -

Like the initialization block, the condition block is also optional. If you are omitting this expression, you must make sure to break the loop in the body in order to not create an infinite loop.

- -
for (let i = 0;; i++) {
-   console.log(i);
-   if (i > 3) break;
-   // more statements
-}
- -

You can also omit all three blocks. Again, make sure to use a {{jsxref("Statements/break", "break")}} statement to end the loop and also modify (increase) a variable, so that the condition for the break statement is true at some point.

- -
var i = 0;
-
-for (;;) {
-  if (i > 3) break;
-  console.log(i);
-  i++;
-}
-
- -

Using for without a statement

- -

The following for cycle calculates the offset position of a node in the final-expression section, and therefore it does not require the use of a statement section, a semicolon is used instead.

- -
function showOffsetPos(sId) {
-
-  var nLeft = 0, nTop = 0;
-
-  for (
-
-    var oItNode = document.getElementById(sId); /* initialization */
-
-    oItNode; /* condition */
-
-    nLeft += oItNode.offsetLeft, nTop += oItNode.offsetTop, oItNode = oItNode.offsetParent /* final-expression */
-
-  ); /* semicolon */
-
-  console.log('Offset position of \'' + sId + '\' element:\n left: ' + nLeft + 'px;\n top: ' + nTop + 'px;');
-
-}
-
-/* Example call: */
-
-showOffsetPos('content');
-
-// Output:
-// "Offset position of "content" element:
-// left: 0px;
-// top: 153px;"
- -
Note: This is one of the few cases in JavaScript where the semicolon is mandatory. Indeed, without the semicolon the line that follows the cycle declaration will be considered a statement.
- -

Especificações

- - - - - - - - - - -
Especificação
{{SpecName('ESDraft', '#sec-for-statement', 'for statement')}}
- -

Compatibilidade de navegador

- - - -

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

- -

Consulte também

- - diff --git a/files/pt-pt/web/javascript/reference/statements/index.html b/files/pt-pt/web/javascript/reference/statements/index.html deleted file mode 100644 index 723804e53a..0000000000 --- a/files/pt-pt/web/javascript/reference/statements/index.html +++ /dev/null @@ -1,151 +0,0 @@ ---- -title: Declarações e instruções -slug: Web/JavaScript/Reference/Statements -tags: - - JavaScript - - Referencia - - declarações - - instruções -translation_of: Web/JavaScript/Reference/Statements -original_slug: Web/JavaScript/Reference/Extratos_e_declarações ---- -
{{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.

- -

Declarações e instruções por categoria

- -

For an alphabetical listing see the sidebar on the left.

- -

Controlo de Fluxo

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

Declarações

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

Funções e classes

- -
-
{{jsxref("Statements/function", "function")}}
-
Declara as funções com parâmetros especificados.
-
{{jsxref("Statements/function*", "function*")}}
-
Generators functions enable writing iterators more easily.
-
{{jsxref("Statements/async_function", "async function")}}
-
Declares an async function with the specified parameters.
-
{{jsxref("Statements/return", "return")}}
-
Specifies the value to be returned by a function.
-
{{jsxref("Statements/class", "class")}}
-
Declara uma Classe.
-
- -

Iterações

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

Outros

- -
-
{{jsxref("Statements/debugger", "debugger")}}
-
Invokes any available debugging functionality. If no debugging functionality is available, this statement has no effect.
-
{{jsxref("Statements/export", "export")}}
-
Used to export functions to make them available for imports in external modules, another scripts.
-
{{jsxref("Statements/import", "import")}}
-
Used to import functions exported from an external module, another script.
-
import.meta
-
A meta-property exposing context-specific metadata to a JavaScript module.
-
{{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.
-
- -

Especificações

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

Compatibilidade de navegador

- - - -

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

- -

Consultar também

- - diff --git a/files/pt-pt/web/javascript/reference/statements/return/index.html b/files/pt-pt/web/javascript/reference/statements/return/index.html deleted file mode 100644 index 54d99d85c3..0000000000 --- a/files/pt-pt/web/javascript/reference/statements/return/index.html +++ /dev/null @@ -1,149 +0,0 @@ ---- -title: return -slug: Web/JavaScript/Reference/Statements/return -tags: - - Declaração - - JavaScript -translation_of: Web/JavaScript/Reference/Statements/return -original_slug: Web/JavaScript/Reference/Extratos_e_declarações/return ---- -
{{jsSidebar("Statements")}}
- -

The return statement ends function execution and specifies a value to be returned to the function caller.

- -

Sintaxe

- -
return [[expression]]; 
- -
-
expression
-
The expression whose value is to be returned. If omitted, undefined is returned instead.
-
- -

Descrição

- -

When a return statement is used in a function body, the execution of the function is stopped. If specified, a given value is returned to the function caller. For example, the following function returns the square of its argument, x, where x is a number.

- -
function square(x) {
-   return x * x;
-}
-var demo = square(3);
-// demo will equal 9
-
- -

If the value is omitted, undefined is returned instead.

- -

The following return statements all break the function execution:

- -
return;
-return true;
-return false;
-return x;
-return x + y / 3;
-
- -

Inserção Automática de Ponto e Vírgula

- -

The return statement is affected by automatic semicolon insertion (ASI). No line terminator is allowed between the return keyword and the expression.

- -
return
-a + b;
-
- -

is transformed by ASI into:

- -
return;
-a + b;
-
- -

The console will warn "unreachable code after return statement".

- -
Starting with Gecko 40 {{geckoRelease(40)}}, a warning is shown in the console if unreachable code is found after a return statement.
- -

Exemplos

- -

Interromper uma função

- -

A function immediately stops at the point where return is called.

- -
function counter() {
-  for (var count = 1; ; count++) {  // infinite loop
-    console.log(count + 'A'); // until 5
-      if (count === 5) {
-        return;
-      }
-      console.log(count + 'B');  // until 4
-    }
-  console.log(count + 'C');  // never appears
-}
-
-counter();
-
-// Output:
-// 1A
-// 1B
-// 2A
-// 2B
-// 3A
-// 3B
-// 4A
-// 4B
-// 5A
-
- -

Devolver uma função

- -

See also the article about Closures.

- -
function magic(x) {
-  return function calc(x) { return x * 42; };
-}
-
-var answer = magic();
-answer(1337); // 56154
-
- -

Especificações

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition.
{{SpecName('ES5.1', '#sec-12.9', 'Return statement')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-return-statement', 'Return statement')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-return-statement', 'Return statement')}}{{Spec2('ESDraft')}} 
- -

Compatibilidade de navegador

- - - -

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

- -

Consulte também

- - diff --git a/files/pt-pt/web/javascript/reference/statements/throw/index.html b/files/pt-pt/web/javascript/reference/statements/throw/index.html deleted file mode 100644 index 59a0e32938..0000000000 --- a/files/pt-pt/web/javascript/reference/statements/throw/index.html +++ /dev/null @@ -1,272 +0,0 @@ ---- -title: throw -slug: Web/JavaScript/Reference/Statements/throw -tags: - - Comando - - Declaração - - JavaScript -translation_of: Web/JavaScript/Reference/Statements/throw -original_slug: Web/JavaScript/Reference/Extratos_e_declarações/throw ---- -
{{jsSidebar("Statements")}}
- -

A declaração throw lança uma exeção definida pelo utilizador. A execução da função atual irá parar (os comandos depois de throw não serão executados), e o controle será passado para o primeiro bloco catch no conjunto de chamadas. Se não existir nenhum bloco catch entre as funções de caller, o programa irá terminar.

- -

Sintaxe

- -
expressão throw; 
- -
-
expressão
-
A expressão para throw.
-
- -

Descrição

- -

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

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

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

- -

Exemplos

- -

Throw um objeto

- -

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

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

Outro exemplo de throwing um objeto

- -

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

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

Rethrow uma exceção

- -

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

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

Especificações

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.4
{{SpecName('ES5.1', '#sec-12.13', 'throw statement')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-throw-statement', 'throw statement')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-throw-statement', 'throw statement')}}{{Spec2('ESDraft')}} 
- -

Compatibilidade de navegador

- - - -

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

- -

Consulte também

- - - -
- - - - - -
diff --git a/files/pt-pt/web/javascript/shells/index.html b/files/pt-pt/web/javascript/shells/index.html deleted file mode 100644 index f6ad6e93eb..0000000000 --- a/files/pt-pt/web/javascript/shells/index.html +++ /dev/null @@ -1,30 +0,0 @@ ---- -title: JavaScript Shells -slug: Web/JavaScript/Shells -tags: - - Extensões:Ferramentas - - Ferramentas - - JavaScript - - JavaScript:Ferramentas -original_slug: JavaScript_Shells ---- -

Um shell JavaScript permite a você rapidamente testar partes de código JavaScript sem ter que atualizar a página web. Eles são extremamente úteis para desenvolvimento e depuração de código.

- -

Lista de shells JavaScript

- -

Os seguintes shells JavaScript trabalham com o Mozilla:

- - - -

Categorias

- -

Add Interwiki Languages

-- cgit v1.2.3-54-g00ecf