diff options
author | Peter Bengtsson <mail@peterbe.com> | 2020-12-08 14:42:52 -0500 |
---|---|---|
committer | Peter Bengtsson <mail@peterbe.com> | 2020-12-08 14:42:52 -0500 |
commit | 074785cea106179cb3305637055ab0a009ca74f2 (patch) | |
tree | e6ae371cccd642aa2b67f39752a2cdf1fd4eb040 /files/pt-pt/web/javascript | |
parent | da78a9e329e272dedb2400b79a3bdeebff387d47 (diff) | |
download | translated-content-074785cea106179cb3305637055ab0a009ca74f2.tar.gz translated-content-074785cea106179cb3305637055ab0a009ca74f2.tar.bz2 translated-content-074785cea106179cb3305637055ab0a009ca74f2.zip |
initial commit
Diffstat (limited to 'files/pt-pt/web/javascript')
78 files changed, 16224 insertions, 0 deletions
diff --git a/files/pt-pt/web/javascript/estruturas_de_dados/index.html b/files/pt-pt/web/javascript/estruturas_de_dados/index.html new file mode 100644 index 0000000000..8b8578229b --- /dev/null +++ b/files/pt-pt/web/javascript/estruturas_de_dados/index.html @@ -0,0 +1,297 @@ +--- +title: Tipos de dados de JavaScript e estruturas de dados +slug: Web/JavaScript/Estruturas_de_dados +tags: + - JavaScript + - Principiante + - Tipos +translation_of: Web/JavaScript/Data_structures +--- +<div>{{jsSidebar("More")}}</div> + +<p>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.</p> + +<h2 id="Digitação_dinâmica">Digitação dinâmica</h2> + +<p>JavaScript is a <em>loosely typed</em> or a <em>dynamic</em> 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:</p> + +<pre class="brush: js">var foo = 42; // foo is now a Number +var foo = 'bar'; // foo is now a String +var foo = true; // foo is now a Boolean +</pre> + +<h2 id="Tipos_de_dados">Tipos de dados</h2> + +<p>The latest ECMAScript standard defines seven data types:</p> + +<ul> + <li>Six data types that are {{Glossary("Primitive", "primitives")}}: + <ul> + <li>{{Glossary("Boolean")}}</li> + <li>{{Glossary("Null")}}</li> + <li>{{Glossary("Undefined")}}</li> + <li>{{Glossary("Number")}}</li> + <li>{{Glossary("String")}}</li> + <li>{{Glossary("Symbol")}} (new in ECMAScript 6)</li> + </ul> + </li> + <li>and {{Glossary("Object")}}</li> +</ul> + +<h2 id="Valores_primitivos">Valores primitivos</h2> + +<p>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".</p> + +<h3 id="Tipo_booleano">Tipo booleano</h3> + +<p>Boolean represents a logical entity and can have two values: <code>true</code>, and <code>false</code>.</p> + +<h3 id="Tipo_Null">Tipo <em>Null</em></h3> + +<p>The Null type has exactly one value: <code>null</code>. See {{jsxref("null")}} and {{Glossary("Null")}} for more details.</p> + +<h3 id="Tipo_indefinido">Tipo indefinido</h3> + +<p>A variable that has not been assigned a value has the value <code>undefined</code>. See {{jsxref("undefined")}} and {{Glossary("Undefined")}} for more details.</p> + +<h3 id="Tipo_número">Tipo número</h3> + +<p>According to the ECMAScript standard, there is only one number type: the <a href="http://en.wikipedia.org/wiki/Double_precision_floating-point_format">double-precision 64-bit binary format IEEE 754 value</a> (number between -(2<sup>53</sup> -1) and 2<sup>53</sup> -1). <strong>There is no specific type for integers</strong>. In addition to being able to represent floating-point numbers, the number type has three symbolic values: <code>+Infinity</code>, <code>-Infinity</code>, and <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/NaN"><code>NaN</code></a> (not-a-number).</p> + +<p>To check for the largest available value or smallest available value within <code>+/-Infinity</code>, 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.</p> + +<p>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 <code>+0 === -0</code> is <code>true</code>. However, you are able to notice this when you divide by zero:</p> + +<pre class="brush: js">> 42 / +0 +Infinity +> 42 / -0 +-Infinity +</pre> + +<p>Although a number often represents only its value, JavaScript provides <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators" title="en/JavaScript/Reference/Operators/Bitwise_Operators">some binary operators</a>. These can be used to represent several Boolean values within a single number using <a class="external" href="http://en.wikipedia.org/wiki/Mask_%28computing%29">bit masking</a>. 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.</p> + +<h3 id="Tipo_string">Tipo <em>string</em></h3> + +<p>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.</p> + +<p>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:</p> + +<ul> + <li>A substring of the original by picking individual letters or using {{jsxref("String.substr()")}}.</li> + <li>A concatenation of two strings using the concatenation operator (<code>+</code>) or {{jsxref("String.concat()")}}.</li> +</ul> + +<h4 id="Beware_of_stringly-typing_your_code!">Beware of "stringly-typing" your code!</h4> + +<p>It can be tempting to use strings to represent complex data. Doing this comes with short-term benefits:</p> + +<ul> + <li>It is easy to build complex strings with concatenation.</li> + <li>Strings are easy to debug (what you see printed is always what is in the string).</li> + <li>Strings are the common denominator of a lot of APIs (<a href="/en-US/docs/Web/API/HTMLInputElement" title="HTMLInputElement">input fields</a>, <a href="/en-US/docs/Storage" title="Storage">local storage</a> values, {{ domxref("XMLHttpRequest") }} responses when using <code>responseText</code>, etc.) and it can be tempting to only work with strings.</li> +</ul> + +<p>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.</p> + +<p>Use strings for textual data. When representing complex data, parse strings and use the appropriate abstraction.</p> + +<h3 id="Tipo_símbolo">Tipo símbolo</h3> + +<p>Symbols are new to JavaScript in ECMAScript Edition 6. A Symbol is a <strong>unique</strong> and <strong>immutable</strong> 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.</p> + +<h2 id="Objetos">Objetos</h2> + +<p>In computer science, an object is a value in memory which is possibly referenced by an {{Glossary("Identifier", "identifier")}}.</p> + +<h3 id="Propriedades">Propriedades</h3> + +<p>In JavaScript, objects can be seen as a collection of properties. With the <a href="/en-US/docs/Web/JavaScript/Guide/Values,_variables,_and_literals#Object_literals">object literal syntax</a>, 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.</p> + +<p>There are two types of object properties which have certain attributes: The data property and the accessor property.</p> + +<h4 id="Data_property">Data property</h4> + +<p>Associates a key with a value and has the following attributes:</p> + +<table class="standard-table"> + <caption>Attributes of a data property</caption> + <tbody> + <tr> + <th>Attribute</th> + <th>Type</th> + <th>Description</th> + <th>Default value</th> + </tr> + <tr> + <td>[[Value]]</td> + <td>Any JavaScript type</td> + <td>The value retrieved by a get access of the property.</td> + <td>undefined</td> + </tr> + <tr> + <td>[[Writable]]</td> + <td>Boolean</td> + <td>If <code>false</code>, the property's [[Value]] can't be changed.</td> + <td>false</td> + </tr> + <tr> + <td>[[Enumerable]]</td> + <td>Boolean</td> + <td>If <code>true</code>, the property will be enumerated in <a href="/en-US/docs/Web/JavaScript/Reference/Statements/for...in">for...in</a> loops. See also <a href="/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties">Enumerability and ownership of properties</a></td> + <td>false</td> + </tr> + <tr> + <td>[[Configurable]]</td> + <td>Boolean</td> + <td>If <code>false</code>, the property can't be deleted and attributes other than [[Value]] and [[Writable]] can't be changed.</td> + <td>false</td> + </tr> + </tbody> +</table> + +<table class="standard-table"> + <caption>Obsolete attributes (as of ECMAScript 3, renamed in ECMAScript 5)</caption> + <tbody> + <tr> + <th>Attribute</th> + <th>Type</th> + <th>Description</th> + </tr> + <tr> + <td>Read-only</td> + <td>Boolean</td> + <td>Reversed state of the ES5 [[Writable]] attribute.</td> + </tr> + <tr> + <td>DontEnum</td> + <td>Boolean</td> + <td>Reversed state of the ES5 [[Enumerable]] attribute.</td> + </tr> + <tr> + <td>DontDelete</td> + <td>Boolean</td> + <td>Reversed state of the ES5 [[Configurable]] attribute.</td> + </tr> + </tbody> +</table> + +<h4 id="Accessor_property">Accessor property</h4> + +<p>Associates a key with one or two accessor functions (get and set) to retrieve or store a value and has the following attributes:</p> + +<table class="standard-table"> + <caption>Attributes of an accessor property</caption> + <tbody> + <tr> + <th>Attribute</th> + <th>Type</th> + <th>Description</th> + <th>Default value</th> + </tr> + <tr> + <td>[[Get]]</td> + <td>Function object or undefined</td> + <td>The function is called with an empty argument list and retrieves the property value whenever a get access to the value is performed. See also <a href="/en-US/docs/Web/JavaScript/Reference/Operators/get"><code>get</code></a>.</td> + <td>undefined</td> + </tr> + <tr> + <td>[[Set]]</td> + <td>Function object or undefined</td> + <td>The 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 <a href="/en-US/docs/Web/JavaScript/Reference/Operators/set"><code>set</code></a>.</td> + <td>undefined</td> + </tr> + <tr> + <td>[[Enumerable]]</td> + <td>Boolean</td> + <td>If <code>true</code>, the property will be enumerated in <a href="/en-US/docs/Web/JavaScript/Reference/Statements/for...in">for...in</a> loops.</td> + <td>false</td> + </tr> + <tr> + <td>[[Configurable]]</td> + <td>Boolean</td> + <td>If <code>false</code>, the property can't be deleted and can't be changed to a data property.</td> + <td>false</td> + </tr> + </tbody> +</table> + +<div class="note"> +<p><strong>Note: </strong>Attribute is usually used by JavaScript engine, so you can't directly access it(see more about <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty">Object.defineProperty()</a>).That's why the attribute is put in double square brackets instead of single.</p> +</div> + +<h3 id="Objetos_Normal_e_funções">Objetos "Normal", e funções</h3> + +<p>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 <a class="external" href="http://en.wikipedia.org/wiki/Hash_table">hashmaps</a>.</p> + +<p>Functions are regular objects with the additional capability of being callable.</p> + +<h3 id="Dates"><em>Dates</em></h3> + +<p>When representing dates, the best choice is to use the built-in <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date"><code>Date</code> utility</a> in JavaScript.</p> + +<h3 id="Coleções_indexadas_Arrays_e_Arrays_digitados">Coleções indexadas: <em>Arrays </em>e <em>Arrays </em>digitados</h3> + +<p><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Array" title="Array">Arrays</a> are regular objects for which there is a particular relationship between integer-key-ed properties and the 'length' property. Additionally, arrays inherit from <code>Array.prototype</code> which provides to them a handful of convenient methods to manipulate arrays. For example, <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf" title="en/JavaScript/Reference/Global_Objects/Array/indexOf">indexOf</a></code> (searching a value in the array) or <code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Array/push" title="en/JavaScript/Reference/Global_Objects/Array/push">push</a></code> (adding an element to the array), etc. This makes Arrays a perfect candidate to represent lists or sets.</p> + +<p><a href="/en-US/docs/Web/JavaScript/Typed_arrays">Typed Arrays</a> 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:</p> + +<p>{{page("/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray", "TypedArray_objects", "", 0, 3)}}</p> + +<h3 id="Keyed_collections_Maps_Sets_WeakMaps_WeakSets">Keyed collections: Maps, Sets, WeakMaps, WeakSets</h3> + +<p>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.</p> + +<p>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.</p> + +<p>Usually, to bind data to a DOM node, one could set properties directly on the object or use <code>data-*</code> 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.</p> + +<h3 id="Structured_data_JSON">Structured data: JSON</h3> + +<p>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.</p> + +<h3 id="More_objects_in_the_standard_library">More objects in the standard library</h3> + +<p>JavaScript has a standard library of built-in objects. Please have a look at the <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects">reference</a> to find out about more objects.</p> + +<h2 id="Determining_types_using_the_typeof_operator">Determining types using the <code>typeof</code> operator</h2> + +<p>The <code>typeof</code> operator can help you to find the type of your variable. Please read the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof">reference page</a> for more details and edge cases.</p> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-8', 'Types')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-ecmascript-data-types-and-values', 'ECMAScript Data Types and Values')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-ecmascript-data-types-and-values', 'ECMAScript Data Types and Values')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Consulte_também">Consulte também</h2> + +<ul> + <li><a class="link-https" href="https://github.com/nzakas/computer-science-in-javascript/">Nicholas Zakas collection of common data structure and common algorithms in JavaScript.</a></li> + <li><a href="https://github.com/monmohan/DataStructures_In_Javascript" title="https://github.com/monmohan/DataStructures_In_Javascript">Search Tre(i)es implemented in JavaScript</a></li> +</ul> diff --git a/files/pt-pt/web/javascript/gestao_memoria/index.html b/files/pt-pt/web/javascript/gestao_memoria/index.html new file mode 100644 index 0000000000..56bfec0f7f --- /dev/null +++ b/files/pt-pt/web/javascript/gestao_memoria/index.html @@ -0,0 +1,187 @@ +--- +title: Gestão de memória +slug: Web/JavaScript/Gestao_Memoria +tags: + - Desempenho + - JavaScript + - memoria +translation_of: Web/JavaScript/Memory_Management +--- +<div>{{JsSidebar("Advanced")}}</div> + +<h2 id="Introdução">Introdução</h2> + +<p>Linguagens de baixo nível, como o C, têm funções pimitivas de gestão de memória, como por exemplo, <code>malloc()</code> e <code>free()</code>. 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 <em>coleção do lixo</em>. 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.</p> + +<h2 id="Ciclo_da_duração_da_memória">Ciclo da duração da memória</h2> + +<p>Independentemente da linguagem de programação, o ciclo da duração da memória é praticamente sempre o mesmo:</p> + +<ol> + <li>Alocação da memória necessária</li> + <li>Utilização da memória alocada ( leitura, escrita )</li> + <li>Libertar a memória alocada quando já não é necessária</li> +</ol> + +<p>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.</p> + +<h3 id="Alocação_no_JavaScript">Alocação no JavaScript</h3> + +<h4 id="Inicialização_do_valor">Inicialização do valor</h4> + +<p>Com o intuito de não incomodar o programador com alocações, o JavaScript fá-lo juntamente com a declaração de valores.</p> + +<pre class="brush: js">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); +</pre> + +<h4 id="Alocação_através_de_chamadas_de_funções">Alocação através de chamadas de funções</h4> + +<p>Algumas chamadas de funções resultam na alocação de um objeto.</p> + +<pre class="brush: js">var d = new Date(); // alocação de um objeto <em>Date</em> + +var e = document.createElement('div'); // alocação de um elemento DOM</pre> + +<p>Alguns métodos alocam novos valores ou objetos:</p> + +<pre class="brush: js">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 <em>a</em> e <em>a2</em> +</pre> + +<h3 id="Utilização_de_valores">Utilização de valores</h3> + +<p>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.</p> + +<h3 id="Remoção_quando_a_memória_já_não_é_necessária">Remoção quando a memória já não é necessária</h3> + +<p>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.</p> + +<p>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, é <a class="external" href="https://pt.wikipedia.org/wiki/Decidibilidade">indecisível</a> ( não pode ser solucionado por um algoritmo ).</p> + +<h2 id="Coleção_de_lixo">Coleção de lixo</h2> + +<p>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.</p> + +<h3 id="Referências">Referências</h3> + +<p>A noção principal dos algoritmos de coleção de lixo baseiam-se na noção de <em>referência</em>. 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 <a href="https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Guide/Inheritance_and_the_prototype_chain">protótipo</a> ( referência implícita ) e aos valores das suas propriedades ( referência explícita ).</p> + +<p>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 ).</p> + +<h3 id="Contagem_de_referências_na_coleção_de_lixo">Contagem de referências na coleção de lixo</h3> + +<p>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.</p> + +<h4 id="Exemplo">Exemplo</h4> + +<pre class="brush: js">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. +</pre> + +<h4 id="Limitação_ciclos">Limitação: ciclos</h4> + +<p>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 .</p> + +<pre class="brush: js">function f() { + var o = {}; + var o2 = {}; + o.a = o2; // o referencia o2 + o2.a = o; // o2 referencia o + + return 'azerty'; +} + +f(); +</pre> + +<h4 id="Exemplo_de_aplicação_real">Exemplo de aplicação real</h4> + +<p>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:</p> + +<pre class="brush: js">var div; +window.onload = function() { + div = document.getElementById('myDivElement'); + div.circularReference = div; + div.lotsOfData = new Array(10000).join('*'); +}; +</pre> + +<p>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.</p> + +<h3 id="Algoritmo_de_marcação_e_limpeza">Algoritmo de marcação e limpeza</h3> + +<p>Este algoritmo reduz a definição de "um objeto já não é necessário" para "um objeto é inalcançável".</p> + +<p>Este algoritmo assume o conhecimento de um conjunto de objetos chamados "roots" ( em JavaScript, a <em>root</em> - 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.</p> + +<p>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.</p> + +<p>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".</p> + +<h4 id="Os_ciclos_já_não_são_um_problema.">Os ciclos já não são um problema.</h4> + +<p>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.</p> + +<h4 id="Limitações_os_objetos_necessitam_de_ser_explicitamente_inalcançáveis">Limitações: os objetos necessitam de ser explicitamente inalcançáveis</h4> + +<p>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.</p> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li><a class="external" href="http://www.ibm.com/developerworks/web/library/wa-memleak/">Aritgo da IBM sobre "Padrões de percas de memória no JavaScript" (2007)</a></li> + <li><a class="external" href="http://msdn.microsoft.com/en-us/magazine/ff728624.aspx">Artigo da Kangax sobre como registar um apontador de evento e evitar percas de memória (2010)</a></li> + <li><a href="https://developer.mozilla.org/pt-PT/docs/Mozilla/Performance" title="https://developer.mozilla.org/en-US/docs/Mozilla/Performance">Desempenho</a></li> +</ul> diff --git a/files/pt-pt/web/javascript/guia/detalhes_do_modelo_de_objeto/index.html b/files/pt-pt/web/javascript/guia/detalhes_do_modelo_de_objeto/index.html new file mode 100644 index 0000000000..01de143289 --- /dev/null +++ b/files/pt-pt/web/javascript/guia/detalhes_do_modelo_de_objeto/index.html @@ -0,0 +1,735 @@ +--- +title: Detalhes do modelo de objeto +slug: Web/JavaScript/Guia/Detalhes_do_modelo_de_objeto +tags: + - Guia(2) + - Intermediário + - JavaScript + - Objeto +translation_of: Web/JavaScript/Guide/Details_of_the_Object_Model +--- +<div>{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Working_with_Objects", "Web/JavaScript/Guide/Iterators_and_Generators")}}</div> + +<div class="note"> +<p>The content of this article is under discussion. Please provide feedback and help us to make this page better: {{bug(1201380)}}.</p> +</div> + +<p class="summary">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.</p> + +<p>This chapter assumes that you are already somewhat familiar with JavaScript and that you have used JavaScript functions to create simple objects.</p> + +<h2 id="Linguagens_com_base_em_classe_versus_protótipo">Linguagens com base em classe versus protótipo</h2> + +<p>Class-based object-oriented languages, such as Java and C++, are founded on the concept of two distinct entities: classes and instances.</p> + +<ul> + <li>A <em>class</em> defines all of the properties (considering methods and fields in Java, or members in C++, to be properties) that characterize a certain set of objects. A class is an abstract thing, rather than any particular member of the set of objects it describes. For example, the <code>Employee</code> class could represent the set of all employees.</li> + <li>An <em>instance</em>, on the other hand, is the instantiation of a class; that is, one of its members. For example, <code>Victoria</code> could be an instance of the <code>Employee</code> class, representing a particular individual as an employee. An instance has exactly the same properties of its parent class (no more, no less).</li> +</ul> + +<p>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 <em>prototypical object</em>, 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 <em>prototype</em> for another object, allowing the second object to share the first object's properties.</p> + +<h3 id="Definição_de_uma_classe">Definição de uma classe</h3> + +<p>In class-based languages, you define a class in a separate <em>class definition</em>. In that definition you can specify special methods, called <em>constructors</em>, 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 <code>new</code> operator in association with the constructor method to create class instances.</p> + +<p>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 <code>new</code> operator with a constructor function to create a new object.</p> + +<h3 id="Subclasses_e_sucessão">Subclasses e sucessão</h3> + +<p>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 <em>subclass</em> 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 <code>Employee</code> class includes only the <code>name</code> and <code>dept</code> properties, and <code>Manager</code> is a subclass of <code>Employee</code> that adds the <code>reports</code> property. In this case, an instance of the <code>Manager</code> class would have all three properties: <code>name</code>, <code>dept</code>, and <code>reports</code>.</p> + +<p>JavaScript implements inheritance by allowing you to associate a prototypical object with any constructor function. So, you can create exactly the <code>Employee</code> — <code>Manager</code> example, but you use slightly different terminology. First you define the <code>Employee</code> constructor function, specifying the <code>name</code> and <code>dept</code> properties. Next, you define the <code>Manager</code> constructor function, calling the <code>Empl</code><code>oyee</code> constructor and specifying the <code>reports</code> property. Finally, you assign a new object derived from <code>Employee.prototype</code> as the <code>prototype</code> for the <code>Manager</code> constructor function. Then, when you create a new <code>Manager</code>, it inherits the <code>name</code> and <code>dept</code> properties from the <code>Employee</code> object.</p> + +<h3 id="Adição_e_remoção_de_propriedades">Adição e remoção de propriedades</h3> + +<p>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.</p> + +<h3 id="Resumo_das_diferenças">Resumo das diferenças</h3> + +<p>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.</p> + +<table class="standard-table"> + <caption>Comparison of class-based (Java) and prototype-based (JavaScript) object systems</caption> + <thead> + <tr> + <th scope="col">Com base em Classe (Java)</th> + <th scope="col">Com base em Protótipo (JavaScript)</th> + </tr> + </thead> + <tbody> + <tr> + <td>Class and instance are distinct entities.</td> + <td>All objects can inherit from another object.</td> + </tr> + <tr> + <td>Define a class with a class definition; instantiate a class with constructor methods.</td> + <td>Define and create a set of objects with constructor functions.</td> + </tr> + <tr> + <td>Create a single object with the <code>new</code> operator.</td> + <td>Same.</td> + </tr> + <tr> + <td>Construct an object hierarchy by using class definitions to define subclasses of existing classes.</td> + <td>Construct an object hierarchy by assigning an object as the prototype associated with a constructor function.</td> + </tr> + <tr> + <td>Inherit properties by following the class chain.</td> + <td>Inherit properties by following the prototype chain.</td> + </tr> + <tr> + <td>Class definition specifies <em>all</em> properties of all instances of a class. Cannot add properties dynamically at run time.</td> + <td>Constructor function or prototype specifies an <em>initial set</em> of properties. Can add or remove properties dynamically to individual objects or to the entire set of objects.</td> + </tr> + </tbody> +</table> + +<h2 id="The_employee_example">The employee example</h2> + +<p>The remainder of this chapter uses the employee hierarchy shown in the following figure.</p> + +<div style="display: table-row;"> +<div style="display: table-cell; width: 350px; text-align: center; vertical-align: middle; padding: 10px;"> +<p>A simple object hierarchy with the following objects:</p> + +<p><img alt="" src="https://mdn.mozillademos.org/files/3060/figure8.1.png"></p> +</div> + +<div style="display: table-cell; vertical-align: middle; padding: 10px;"> +<ul> + <li><code>Employee</code> has the properties <code>name</code> (whose value defaults to the empty string) and <code>dept</code> (whose value defaults to "general").</li> + <li><code>Manager</code> is based on <code>Employee</code>. It adds the <code>reports</code> property (whose value defaults to an empty array, intended to have an array of <code>Employee</code> objects as its value).</li> + <li><code>WorkerBee</code> is also based on <code>Employee</code>. It adds the <code>projects</code> property (whose value defaults to an empty array, intended to have an array of strings as its value).</li> + <li><code>SalesPerson</code> is based on <code>WorkerBee</code>. It adds the <code>quota</code> property (whose value defaults to 100). It also overrides the <code>dept</code> property with the value "sales", indicating that all salespersons are in the same department.</li> + <li><code>Engineer</code> is based on <code>WorkerBee</code>. It adds the <code>machine</code> property (whose value defaults to the empty string) and also overrides the <code>dept</code> property with the value "engineering".</li> +</ul> +</div> +</div> + +<h2 id="Criação_de_hierarquia">Criação de hierarquia</h2> + +<p>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.</p> + +<p>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.</p> + +<p>In a real application, you would probably define constructors that allow you to provide property values at object creation time (see <a href="#More_flexible_constructors">More flexible constructors</a> for information). For now, these simple definitions demonstrate how the inheritance occurs.</p> + +<p>The following Java and JavaScript <code>Employee</code> 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 <a href="http://en.wikipedia.org/wiki/Strong_and_weak_typing">strongly typed language</a> while JavaScript is a weakly typed language).</p> + +<div class="twocolumns"> +<h4 id="JavaScript">JavaScript</h4> + +<pre class="brush: js">function Employee() { + this.name = ""; + this.dept = "general"; +} +</pre> + +<h4 id="Java">Java</h4> + +<pre class="brush: java">public class Employee { + public String name = ""; + public String dept = "general"; +} +</pre> +</div> + +<p>The <code>Manager</code> and <code>WorkerBee</code> 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 <code>prototype</code> 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.</p> + +<div class="twocolumns"> +<h4 id="JavaScript_2">JavaScript</h4> + +<pre class="brush: js">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); +</pre> + +<h4 id="Java_2">Java</h4> + +<pre class="brush: java">public class Manager extends Employee { + public Employee[] reports = new Employee[0]; +} + + + +public class WorkerBee extends Employee { + public String[] projects = new String[0]; +} + + +</pre> +</div> + +<p>The <code>Engineer</code> and <code>SalesPerson</code> definitions create objects that descend from <code>WorkerBee</code> and hence from <code>Employee</code>. 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 <code>dept</code> property with new values specific to these objects.</p> + +<div class="twocolumns"> +<h4 id="JavaScript_3">JavaScript</h4> + +<pre class="brush: js">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); +</pre> + +<h4 id="Java_3">Java</h4> + +<pre class="brush: 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 = ""; +} + +</pre> +</div> + +<p>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.</p> + +<div class="note"> +<p><strong>Nota:</strong> The term <em><em>instance</em></em> 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 <code><code>jane</code></code> is an instance of <code><code>Engineer</code></code>. Similarly, although the terms <em><em>parent</em>, <em>child</em>, <em>ancestor</em></em>, and <em><em>descendant</em></em> do not have formal meanings in JavaScript; you can use them informally to refer to objects higher or lower in the prototype chain.</p> +</div> + +<h3 id="Criação_de_objetos_com_definições_simples">Criação de objetos com definições simples</h3> + +<div class="twocolumns"> +<h4 id="Hierarquia_do_objeto">Hierarquia do objeto</h4> + +<p>The following hierarchy is created using the code on the right side.</p> + +<p><img src="https://mdn.mozillademos.org/files/10412/=figure8.3.png"></p> + +<p> </p> + +<h4 id="individual_objects">individual objects</h4> + +<pre class="brush: js">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 '' +</pre> +</div> + +<h2 id="Propriedades_do_objeto">Propriedades do objeto</h2> + +<p>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.</p> + +<h3 id="Propriedades_de_sucessão">Propriedades de sucessão</h3> + +<p>Suppose you create the <code>mark</code> object as a <code>WorkerBee</code> with the following statement:</p> + +<pre class="brush: js">var mark = new WorkerBee; +</pre> + +<p>When JavaScript sees the <code>new</code> operator, it creates a new generic object and passes this new object as the value of the <code>this</code> keyword to the <code>WorkerBee</code> constructor function. The constructor function explicitly sets the value of the <code>projects</code> property, and implicitly sets the value of the internal <code>__proto__</code> property to the value of <code>WorkerBee.prototype</code>. (That property name has two underscore characters at the front and two at the end.) The <code>__proto__</code> 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 <code>mark</code> to that object.</p> + +<p>This process does not explicitly put values in the <code>mark</code> object (<em>local</em> values) for the properties that <code>mark</code> 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 <code>__proto__</code> 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 <code>mark</code> object has the following properties and values:</p> + +<pre class="brush: js">mark.name = ""; +mark.dept = "general"; +mark.projects = []; +</pre> + +<p>The <code>mark</code> object inherits values for the <code>name</code> and <code>dept</code> properties from the prototypical object in <code>mark.__proto__</code>. It is assigned a local value for the <code>projects</code> property by the <code>WorkerBee</code> constructor. This gives you inheritance of properties and their values in JavaScript. Some subtleties of this process are discussed in <a href="#Property_inheritance_revisited">Property inheritance revisited</a>.</p> + +<p>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 <code>WorkerBee</code>. You can, of course, change the values of any of these properties. So, you could give specific information for <code>mark</code> as follows:</p> + +<pre class="brush: js">mark.name = "Doe, Mark"; +mark.dept = "admin"; +mark.projects = ["navigator"];</pre> + +<h3 id="Adição_de_propriedades">Adição de propriedades</h3> + +<p>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:</p> + +<pre class="brush: js">mark.bonus = 3000; +</pre> + +<p>Now, the <code>mark</code> object has a <code>bonus</code> property, but no other <code>WorkerBee</code> has this property.</p> + +<p>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 <code>specialty</code> property to all employees with the following statement:</p> + +<pre class="brush: js">Employee.prototype.specialty = "none"; +</pre> + +<p>As soon as JavaScript executes this statement, the <code>mark</code> object also has the <code>specialty</code> property with the value of <code>"none"</code>. The following figure shows the effect of adding this property to the <code>Employee</code> prototype and then overriding it for the <code>Engineer</code> prototype.</p> + +<p><img alt="" class="internal" src="/@api/deki/files/4422/=figure8.4.png" style="height: 519px; width: 833px;"><br> + <small><strong>Adding properties</strong></small></p> + +<h2 id="Mais_construtores_flexíveis">Mais construtores flexíveis</h2> + +<p>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.</p> + +<p><img alt="" class="internal" id="figure8.5" src="/@api/deki/files/4423/=figure8.5.png" style="height: 481px; width: 1012px;"><br> + <small><strong>Specifying properties in a constructor, take 1</strong></small></p> + +<p>The following table shows the Java and JavaScript definitions for these objects.</p> + +<div class="twocolumns"> +<h4 id="JavaScript_4">JavaScript</h4> + +<h4 id="Java_4">Java</h4> +</div> + +<div class="twocolumns"> +<pre class="brush: js">function Employee (name, dept) { + this.name = name || ""; + this.dept = dept || "general"; +} +</pre> + +<p> </p> + +<p> </p> + +<p> </p> + +<p> </p> + +<p> </p> + +<pre class="brush: java">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; + } +} +</pre> +</div> + +<div class="twocolumns"> +<pre class="brush: js">function WorkerBee (projs) { + + this.projects = projs || []; +} +WorkerBee.prototype = new Employee; +</pre> + +<p> </p> + +<p> </p> + +<p> </p> + +<pre class="brush: java">public class WorkerBee extends Employee { + public String[] projects; + public WorkerBee () { + this(new String[0]); + } + public WorkerBee (String[] projs) { + projects = projs; + } +} +</pre> +</div> + +<div class="twocolumns"> +<pre class="brush: js"> +function Engineer (mach) { + this.dept = "engineering"; + this.machine = mach || ""; +} +Engineer.prototype = new WorkerBee; +</pre> + +<p> </p> + +<p> </p> + +<p> </p> + +<pre class="brush: java">public class Engineer extends WorkerBee { + public String machine; + public Engineer () { + dept = "engineering"; + machine = ""; + } + public Engineer (String mach) { + dept = "engineering"; + machine = mach; + } +} +</pre> +</div> + +<p>These JavaScript definitions use a special idiom for setting default values:</p> + +<pre class="brush: js">this.name = name || ""; +</pre> + +<p>The JavaScript logical OR operator (<code>||</code>) 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 <code>name</code> has a useful value for the <code>name</code> property. If it does, it sets <code>this.name</code> to that value. Otherwise, it sets <code>this.name</code> to the empty string. This chapter uses this idiom for brevity; however, it can be puzzling at first glance.</p> + +<div class="note"> +<p><strong>Note:</strong> This may not work as expected if the constructor function is called with arguments which convert to <code><code>false</code></code> (like <code>0</code> (zero) and empty string (<code><code>""</code></code>). In this case the default value will be chosen.</p> +</div> + +<p>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 <code>Engineer</code>:</p> + +<pre class="brush: js">var jane = new Engineer("belau"); +</pre> + +<p><code>Jane</code>'s properties are now:</p> + +<pre class="brush: js">jane.name == ""; +jane.dept == "engineering"; +jane.projects == []; +jane.machine == "belau" +</pre> + +<p>Notice that with these definitions, you cannot specify an initial value for an inherited property such as <code>name</code>. If you want to specify an initial value for inherited properties in JavaScript, you need to add more code to the constructor function.</p> + +<p>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.</p> + +<p><img alt="" class="internal" src="/@api/deki/files/4430/=figure8.6.png" style="height: 534px; width: 1063px;"><br> + <small><strong>Specifying properties in a constructor, take 2</strong></small></p> + +<p>Let's look at one of these definitions in detail. Here's the new definition for the <code>Engineer</code> constructor:</p> + +<pre class="brush: js">function Engineer (name, projs, mach) { + this.base = WorkerBee; + this.base(name, "engineering", projs); + this.machine = mach || ""; +} +</pre> + +<p>Suppose you create a new <code>Engineer</code> object as follows:</p> + +<pre class="brush: js">var jane = new Engineer("Doe, Jane", ["navigator", "javascript"], "belau"); +</pre> + +<p>JavaScript follows these steps:</p> + +<ol> + <li>The <code>new</code> operator creates a generic object and sets its <code>__proto__</code> property to <code>Engineer.prototype</code>.</li> + <li>The <code>new</code> operator passes the new object to the <code>Engineer</code> constructor as the value of the <code>this</code> keyword.</li> + <li>The constructor creates a new property called <code>base</code> for that object and assigns the value of the <code>WorkerBee</code> constructor to the <code>base</code> property. This makes the <code>WorkerBee</code> constructor a method of the <code>Engineer</code> object.The name of the<code> base</code> property is not special. You can use any legal property name; <code>base</code> is simply evocative of its purpose.</li> + <li> + <p>The constructor calls the <code>base</code> method, passing as its arguments two of the arguments passed to the constructor (<code>"Doe, Jane"</code> and <code>["navigator", "javascript"]</code>) and also the string <code>"engineering"</code>. Explicitly using <code>"engineering"</code> in the constructor indicates that all <code>Engineer</code> objects have the same value for the inherited <code>dept</code> property, and this value overrides the value inherited from <code>Employee</code>.</p> + </li> + <li>Because <code>base</code> is a method of <code>Engineer</code>, within the call to <code>base</code>, JavaScript binds the <code>this</code> keyword to the object created in Step 1. Thus, the <code>WorkerBee</code> function in turn passes the <code>"Doe, Jane"</code> and <code>"engineering"</code> arguments to the <code>Employee</code> constructor function. Upon return from the <code>Employee</code> constructor function, the <code>WorkerBee</code> function uses the remaining argument to set the <code>projects</code> property.</li> + <li>Upon return from the <code>base</code> method, the <code>Engineer</code> constructor initializes the object's <code>machine</code> property to <code>"belau"</code>.</li> + <li>Upon return from the constructor, JavaScript assigns the new object to the <code>jane</code> variable.</li> +</ol> + +<p>You might think that, having called the <code>WorkerBee</code> constructor from inside the <code>Engineer</code> constructor, you have set up inheritance appropriately for <code>Engineer</code> objects. This is not the case. Calling the <code>WorkerBee</code> constructor ensures that an <code>Engineer</code> object starts out with the properties specified in all constructor functions that are called. However, if you later add properties to the <code>Employee</code> or <code>WorkerBee</code> prototypes, those properties are not inherited by the <code>Engineer</code> object. For example, assume you have the following statements:</p> + +<pre class="brush: js">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"; +</pre> + +<p>The <code>jane</code> object does not inherit the <code>specialty</code> property. You still need to explicitly set up the prototype to ensure dynamic inheritance. Assume instead you have these statements:</p> + +<pre class="brush: js">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"; +</pre> + +<p>Now the value of the <code>jane</code> object's <code>specialty</code> property is "none".</p> + +<p>Another way of inheriting is by using the <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call" title="en-US/docs/JavaScript/Reference/Global Objects/Function/call">call()</a></code> / <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply" title="en-US/docs/JavaScript/Reference/Global Objects/Function/apply"><code>apply()</code></a> methods. Below are equivalent:</p> + +<div class="twocolumns"> +<pre class="brush: js">function Engineer (name, projs, mach) { + this.base = WorkerBee; + this.base(name, "engineering", projs); + this.machine = mach || ""; +} +</pre> + +<pre class="brush: js">function Engineer (name, projs, mach) { + WorkerBee.call(this, name, "engineering", projs); + this.machine = mach || ""; +} +</pre> +</div> + +<p>Using the javascript <code>call()</code> method makes a cleaner implementation because the <code>base</code> is not needed anymore.</p> + +<h2 id="Sucessão_de_propriedade_revisitada">Sucessão de propriedade revisitada</h2> + +<p>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.</p> + +<h3 id="Valores_locais_versus_sucedidos">Valores locais versus sucedidos</h3> + +<p>When you access an object property, JavaScript performs these steps, as described earlier in this chapter:</p> + +<ol> + <li>Check to see if the value exists locally. If it does, return that value.</li> + <li>If there is not a local value, check the prototype chain (using the <code>__proto__</code> property).</li> + <li>If an object in the prototype chain has a value for the specified property, return that value.</li> + <li>If no such property is found, the object does not have the property.</li> +</ol> + +<p>The outcome of these steps depends on how you define things along the way. The original example had these definitions:</p> + +<pre class="brush: js">function Employee () { + this.name = ""; + this.dept = "general"; +} + +function WorkerBee () { + this.projects = []; +} +WorkerBee.prototype = new Employee; +</pre> + +<p>With these definitions, suppose you create <code>amy</code> as an instance of <code>WorkerBee</code> with the following statement:</p> + +<pre class="brush: js">var amy = new WorkerBee; +</pre> + +<p>The <code>amy</code> object has one local property, <code>projects</code>. The values for the <code>name</code> and <code>dept</code> properties are not local to <code>amy</code> and so derive from the <code>amy</code> object's <code>__proto__</code> property. Thus, <code>amy</code> has these property values:</p> + +<pre class="brush: js">amy.name == ""; +amy.dept == "general"; +amy.projects == []; +</pre> + +<p>Now suppose you change the value of the <code>name</code> property in the prototype associated with <code>Employee</code>:</p> + +<pre class="brush: js">Employee.prototype.name = "Unknown" +</pre> + +<p>At first glance, you might expect that new value to propagate down to all the instances of <code>Employee</code>. However, it does not.</p> + +<p>When you create <em>any</em> instance of the <code>Employee</code> object, that instance gets a local value for the <code>name</code> property (the empty string). This means that when you set the <code>WorkerBee</code> prototype by creating a new <code>Employee</code> object, <code>WorkerBee.prototype</code> has a local value for the <code>name</code> property. Therefore, when JavaScript looks up the <code>name</code> property of the <code>amy</code> object (an instance of <code>WorkerBee</code>), JavaScript finds the local value for that property in <code>WorkerBee.prototype</code>. It therefore does not look further up the chain to <code>Employee.prototype</code>.</p> + +<p>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:</p> + +<pre class="brush: js">function Employee () { + this.dept = "general"; +} +Employee.prototype.name = ""; + +function WorkerBee () { + this.projects = []; +} +WorkerBee.prototype = new Employee; + +var amy = new WorkerBee; + +Employee.prototype.name = "Unknown"; +</pre> + +<p>In this case, the <code>name</code> property of <code>amy</code> becomes "Unknown".</p> + +<p>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.</p> + +<h3 id="Determining_instance_relationships">Determining instance relationships</h3> + +<p>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 <code>__proto__</code>. This continues recursively; the process is called "lookup in the prototype chain".</p> + +<p>The special property <code>__proto__</code> is set when an object is constructed; it is set to the value of the constructor's <code>prototype</code> property. So the expression <code>new Foo()</code> creates an object with <code>__proto__ == <code class="moz-txt-verticalline">Foo.prototype</code></code>. Consequently, changes to the properties of <code class="moz-txt-verticalline">Foo.prototype</code> alters the property lookup for all objects that were created by <code>new Foo()</code>.</p> + +<p>Every object has a <code>__proto__</code> object property (except <code>Object</code>); every function has a <code>prototype</code> object property. So objects can be related by 'prototype inheritance' to other objects. You can test for inheritance by comparing an object's <code>__proto__</code> to a function's <code>prototype</code> object. JavaScript provides a shortcut: the <code>instanceof</code> operator tests an object against a function and returns true if the object inherits from the function prototype. For example,</p> + +<pre class="brush: js">var f = new Foo(); +var isTrue = (f instanceof Foo);</pre> + +<p>For a more detailed example, suppose you have the same set of definitions shown in <a href="#Inheriting_properties">Inheriting properties</a>. Create an <code>Engineer</code> object as follows:</p> + +<pre class="brush: js">var chris = new Engineer("Pigman, Chris", ["jsd"], "fiji"); +</pre> + +<p>With this object, the following statements are all true:</p> + +<pre class="brush: js">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; +</pre> + +<p>Given this, you could write an <code>instanceOf</code> function as follows:</p> + +<pre class="brush: js">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; +} +</pre> + +<div class="note"><strong>Note:</strong> 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.</div> + +<p>Using the instanceOf function defined above, these expressions are true:</p> + +<pre class="brush: js">instanceOf (chris, Engineer) +instanceOf (chris, WorkerBee) +instanceOf (chris, Employee) +instanceOf (chris, Object) +</pre> + +<p>But the following expression is false:</p> + +<pre class="brush: js">instanceOf (chris, SalesPerson) +</pre> + +<h3 id="Informação_global_nos_construtores">Informação global nos construtores</h3> + +<p>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 <code>Employee</code>:</p> + +<pre class="brush: js">var idCounter = 1; + +function Employee (name, dept) { + this.name = name || ""; + this.dept = dept || "general"; + this.id = idCounter++; +} +</pre> + +<p>With this definition, when you create a new <code>Employee</code>, the constructor assigns it the next ID in sequence and then increments the global ID counter. So, if your next statement is the following, <code>victoria.id</code> is 1 and <code>harry.id</code> is 2:</p> + +<pre class="brush: js">var victoria = new Employee("Pigbert, Victoria", "pubs") +var harry = new Employee("Tschopik, Harry", "sales") +</pre> + +<p>At first glance that seems fine. However, <code>idCounter</code> gets incremented every time an <code>Employee</code> object is created, for whatever purpose. If you create the entire <code>Employee</code> hierarchy shown in this chapter, the <code>Employee</code> constructor is called every time you set up a prototype. Suppose you have the following code:</p> + +<pre class="brush: js">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"); +</pre> + +<p>Further assume that the definitions omitted here have the <code>base</code> property and call the constructor above them in the prototype chain. In this case, by the time the <code>mac</code> object is created, <code>mac.id</code> is 5.</p> + +<p>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:</p> + +<pre class="brush: js">function Employee (name, dept) { + this.name = name || ""; + this.dept = dept || "general"; + if (name) + this.id = idCounter++; +} +</pre> + +<p>When you create an instance of <code>Employee</code> 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 <code>Employee</code> to get an assigned id, you must specify a name for the employee. In this example, <code>mac.id</code> would be 1.</p> + +<h3 id="No_multiple_inheritance">No multiple inheritance</h3> + +<p>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.</p> + +<p>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.</p> + +<p>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:</p> + +<pre class="brush: js">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") +</pre> + +<p>Further assume that the definition of <code>WorkerBee</code> is as used earlier in this chapter. In this case, the <code>dennis</code> object has these properties:</p> + +<pre class="brush: js">dennis.name == "Doe, Dennis" +dennis.dept == "engineering" +dennis.projects == ["collabra"] +dennis.machine == "hugo" +dennis.hobby == "scuba" +</pre> + +<p>So <code>dennis</code> does get the <code>hobby</code> property from the <code>Hobbyist</code> constructor. However, assume you then add a property to the <code>Hobbyist</code> constructor's prototype:</p> + +<pre class="brush: js">Hobbyist.prototype.equipment = ["mask", "fins", "regulator", "bcd"] +</pre> + +<p>The <code>dennis</code> object does not inherit this new property.</p> + +<div>{{PreviousNext("Web/JavaScript/Guide/Working_with_Objects", "Web/JavaScript/Guide/Iterators_and_Generators")}}</div> diff --git a/files/pt-pt/web/javascript/guia/expressoes_e_operadores/index.html b/files/pt-pt/web/javascript/guia/expressoes_e_operadores/index.html new file mode 100644 index 0000000000..d0c815aac5 --- /dev/null +++ b/files/pt-pt/web/javascript/guia/expressoes_e_operadores/index.html @@ -0,0 +1,832 @@ +--- +title: Expressoes e Operadores +slug: Web/JavaScript/Guia/Expressoes_e_Operadores +--- +<div>{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Functions", "Web/JavaScript/Guide/Numbers_and_dates")}}</div> +<p><span id="result_box" lang="pt"><span class="hps">Este capítulo descreve</span> <span class="hps">expressões e operadores JavaScript</span><span>, incluindo </span></span>atribuição<span id="result_box" lang="pt"><span>, comparação,</span> <span class="hps">aritmética,</span> <span class="hps">bit a bit</span><span>, lógico, string</span><span>, e</span> <span class="hps">operadores especiais.</span></span></p> + +<h2 id="Expressões">Expressões</h2> + +<p>Uma <em>expressão</em> é qualquer unidade de código válida que resolve um valor.</p> + +<p><span id="result_box" lang="pt"><span class="alt-edited hps">Conceitualmente</span><span>, há dois</span> <span class="hps">tipos de expressões</span><span>: aqueles</span> <span class="hps">que</span> <span class="hps">atribui um valor</span> <span class="hps">para</span> <span class="hps">uma variável, e</span> <span class="hps">aqueles</span> <span class="hps">que</span> <span class="hps">simplesmente tem</span> <span class="hps">um valor.</span> <span class="hps">Por exemplo,</span> <span class="hps">a expressão</span> <code><span class="hps">x = 7</span></code> <span class="hps">é uma expressão que</span> <span class="hps">atribui</span> a x <span class="hps">o valor </span><span class="hps">sete.</span> <span class="hps">Esta expressão</span> <span class="hps">avalia</span><span>-se</span> <span class="hps">a sete.</span> <span class="hps">Tais expressões</span> <span class="alt-edited hps">usam <em>operadores de atribuição</em></span><span>.</span> <span class="hps">Por outro lado</span><span>, a expressão de</span> <code><span class="hps">3 + 4</span></code> <span class="hps">simplesmente avalia</span> <span class="hps">a sete</span><span>; ele</span> <span class="hps">não realiza</span> <span class="hps">uma atribuição.</span> <span class="hps">Os</span> <span class="hps">operadores usados</span> <span class="hps">em tais expressões</span> <span class="hps">são referidos</span> <span class="hps">simplesmente como</span> <span class="hps"><em>operadores</em>.</span></span></p> + +<p><span class="short_text" id="result_box" lang="pt"><span class="hps">JavaScript</span> <span class="hps">tem os seguintes tipos</span> <span class="hps">de expressões:</span></span></p> + +<ul> + <li><span id="result_box" lang="pt"><span class="hps">Aritmética:</span> <span class="hps">resulta em um número</span><span>, por exemplo</span> <span class="hps">3,14159.</span></span> (Generally uses {{ web.link("#Arithmetic_operators", "arithmetic operators") }}.)</li> + <li><span id="result_box" lang="pt"><span class="hps">String:</span> <span class="hps">avalia</span> <span class="hps">em</span> <span class="hps">uma cadeia de caracteres</span><span>, por exemplo,</span> <span class="hps">"Fred</span><span>" ou</span> <span class="hps">"234"</span></span>. (Generally uses {{ web.link("#String_operators", "string operators") }}.)</li> + <li>Logical: resulta em verdadeira (true em inglês) ou falsa (false em inglês). (Often involves {{ web.link("#Logical_operators", "logical operators") }}.)</li> + <li>Object: resulta como um objeto. (See {{ web.link("#Special_operators", "special operators") }} for various ones that evaluate to objects.)</li> +</ul> + +<h2 id="Operadores">Operadores</h2> + +<p><span id="result_box" lang="pt"><span class="hps">JavaScript</span> <span class="hps">tem os seguintes tipos</span> <span class="hps">de operadores.</span> <span class="hps">Esta seção</span> <span class="hps">descreve os operadores</span> <span class="hps">e contém informações sobre</span> <span class="hps">a precedência do operador</span><span>.</span></span></p> + +<ul> + <li>{{ web.link("#Assignment_operators", "Assignment operators") }}</li> + <li>{{ web.link("#Comparison_operators", "Comparison operators") }}</li> + <li>{{ web.link("#Arithmetic_operators", "Arithmetic operators") }}</li> + <li>{{ web.link("#Bitwise_operators", "Bitwise operators") }}</li> + <li>{{ web.link("#Logical_operators", "Logical operators") }}</li> + <li>{{ web.link("#String_operators", "String operators") }}</li> + <li>{{ web.link("#Special_operators", "Special operators") }}</li> +</ul> + +<p>JavaScript has both <em>binary</em> and <em>unary</em> operators, and one special ternary operator, the conditional operator. A binary operator requires two operands, one before the operator and one after the operator:</p> + +<pre><em>operand1</em> <em>operator</em> <em>operand2</em> +</pre> + +<p>For example, <code>3+4</code> or <code>x*y</code>.</p> + +<p>A unary operator requires a single operand, either before or after the operator:</p> + +<pre><em>operator</em> <em>operand</em> +</pre> + +<p>or</p> + +<pre><em>operand</em> <em>operator</em> +</pre> + +<p>For example, <code>x++</code> or <code>++x</code>.</p> + +<h3 id="Assignment_operators">Assignment operators</h3> + +<p>An assignment operator assigns a value to its left operand based on the value of its right operand. The basic assignment operator is equal (=), which assigns the value of its right operand to its left operand. That is, x = y assigns the value of y to x.</p> + +<p>The other assignment operators are shorthand for standard operations, as shown in the following table.</p> + +<table class="standard-table"> + <caption>Table 3.1 Assignment operators</caption> + <thead> + <tr> + <th scope="col">Shorthand operator</th> + <th scope="col">Meaning</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>x += y</code></td> + <td><code>x = x + y</code></td> + </tr> + <tr> + <td><code>x -= y</code></td> + <td><code>x = x - y</code></td> + </tr> + <tr> + <td><code>x *= y</code></td> + <td><code>x = x * y</code></td> + </tr> + <tr> + <td><code>x /= y</code></td> + <td><code>x = x / y</code></td> + </tr> + <tr> + <td><code>x %= y</code></td> + <td><code>x = x % y</code></td> + </tr> + <tr> + <td><code>x <<= y</code></td> + <td><code>x = x << y</code></td> + </tr> + <tr> + <td><code>x >>= y</code></td> + <td><code>x = x >> y</code></td> + </tr> + <tr> + <td><code>x >>>= y</code></td> + <td><code>x = x >>> y</code></td> + </tr> + <tr> + <td><code>x &= y</code></td> + <td><code>x = x & y</code></td> + </tr> + <tr> + <td><code>x ^= y</code></td> + <td><code>x = x ^ y</code></td> + </tr> + <tr> + <td><code>x |= y</code></td> + <td><code>x = x | y</code></td> + </tr> + </tbody> +</table> + +<h3 id="Comparison_operators">Comparison operators</h3> + +<p><span class="comment">This seems to me kind of poorly explained, mostly the difference betwen "==" and "==="...</span> A comparison operator compares its operands and returns a logical value based on whether the comparison is true. The operands can be numerical, string, logical, or object values. Strings are compared based on standard lexicographical ordering, using Unicode values. In most cases, if the two operands are not of the same type, JavaScript attempts to convert the operands to an appropriate type for the comparison. (The sole exceptions to this rule are <code>===</code> and <code>!==</code>, which perform "strict" equality and inequality and which do not attempt to convert the operands to compatible types before checking equality.) This generally results in a numerical comparison being performed. The following table describes the comparison operators, assuming the following code:</p> + +<pre class="brush: js">var var1 = 3, var2 = 4; +</pre> + +<table class="standard-table"> + <caption>Table 3.2 Comparison operators</caption> + <thead> + <tr> + <th scope="col">Operator</th> + <th scope="col">Description</th> + <th scope="col">Examples returning true</th> + </tr> + </thead> + <tbody> + <tr> + <td>Equal (<code>==</code>)</td> + <td>Returns true if the operands are equal.</td> + <td><code>3 == var1</code> + <p><code>"3" == var1</code></p> + <code>3 == '3'</code></td> + </tr> + <tr> + <td>Not equal (<code>!=</code>)</td> + <td>Returns true if the operands are not equal.</td> + <td><code>var1 != 4<br> + var2 != "3"</code></td> + </tr> + <tr> + <td>Strict equal (<code>===</code>)</td> + <td>Returns true if the operands are equal and of the same type.</td> + <td><code>3 === var1</code></td> + </tr> + <tr> + <td>Strict not equal (<code>!==</code>)</td> + <td>Returns true if the operands are not equal and/or not of the same type.</td> + <td><code>var1 !== "3"<br> + 3 !== '3'</code></td> + </tr> + <tr> + <td>Greater than (<code>></code>)</td> + <td>Returns true if the left operand is greater than the right operand.</td> + <td><code>var2 > var1<br> + "12" > 2</code></td> + </tr> + <tr> + <td>Greater than or equal (<code>>=</code>)</td> + <td>Returns true if the left operand is greater than or equal to the right operand.</td> + <td><code>var2 >= var1<br> + var1 >= 3</code></td> + </tr> + <tr> + <td>Less than (<code><</code>)</td> + <td>Returns true if the left operand is less than the right operand.</td> + <td><code>var1 < var2<br> + "12" < "2"</code></td> + </tr> + <tr> + <td>Less than or equal (<code><=</code>)</td> + <td>Returns true if the left operand is less than or equal to the right operand.</td> + <td><code>var1 <= var2<br> + var2 <= 5</code></td> + </tr> + </tbody> +</table> + +<h3 id="Arithmetic_operators">Arithmetic operators</h3> + +<p>Arithmetic operators take numerical values (either literals or variables) as their operands and return a single numerical value. The standard arithmetic operators are addition (+), subtraction (-), multiplication (*), and division (/). These operators work as they do in most other programming languages when used with floating point numbers (in particular, note that division by zero produces <a href="/en-US/docs/JavaScript/Reference/Global_Objects/NaN" title="en-US/docs/JavaScript/Reference/Global_Properties/NaN"><code>NaN</code></a>). For example:</p> + +<pre class="brush: js">console.log(1 / 2); /* prints 0.5 */ +console.log(1 / 2 == 1.0 / 2.0); /* also this is true */ +</pre> + +<p>In addition, JavaScript provides the arithmetic operators listed in the following table.</p> + +<table class="fullwidth-table"> + <caption>Table 3.3 Arithmetic operators</caption> + <thead> + <tr> + <th scope="col">Operator</th> + <th scope="col">Description</th> + <th scope="col">Example</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>%</code><br> + (Modulus)</td> + <td>Binary operator. Returns the integer remainder of dividing the two operands.</td> + <td>12 % 5 returns 2.</td> + </tr> + <tr> + <td><code>++</code><br> + (Increment)</td> + <td>Unary operator. Adds one to its operand. If used as a prefix operator (<code>++x</code>), returns the value of its operand after adding one; if used as a postfix operator (<code>x++</code>), returns the value of its operand before adding one.</td> + <td>If <code>x</code> is 3, then <code>++x</code> sets <code>x</code> to 4 and returns 4, whereas <code>x++</code> returns 3 and, only then, sets <code>x</code> to 4.</td> + </tr> + <tr> + <td><code>--</code><br> + (Decrement)</td> + <td>Unary operator. Subtracts one from its operand. The return value is analogous to that for the increment operator.</td> + <td>If <code>x</code> is 3, then <code>--x</code> sets <code>x</code> to 2 and returns 2, whereas <code>x--</code> returns 3 and, only then, sets <code>x</code> to 2.</td> + </tr> + <tr> + <td><code>-</code><br> + (Unary negation)</td> + <td>Unary operator. Returns the negation of its operand.</td> + <td>If <code>x</code> is 3, then <code>-x</code> returns -3.</td> + </tr> + </tbody> +</table> + +<h3 id="Bitwise_operators">Bitwise operators</h3> + +<p>Bitwise operators treat their operands as a set of 32 bits (zeros and ones), rather than as decimal, hexadecimal, or octal numbers. For example, the decimal number nine has a binary representation of 1001. Bitwise operators perform their operations on such binary representations, but they return standard JavaScript numerical values.</p> + +<p>The following table summarizes JavaScript's bitwise operators.</p> + +<table class="standard-table"> + <caption>Table 3.4 Bitwise operators</caption> + <thead> + <tr> + <th scope="col">Operator</th> + <th scope="col">Usage</th> + <th scope="col">Description</th> + </tr> + </thead> + <tbody> + <tr> + <td>Bitwise AND</td> + <td><code>a & b</code></td> + <td>Returns a one in each bit position for which the corresponding bits of both operands are ones.</td> + </tr> + <tr> + <td>Bitwise OR</td> + <td><code>a | b</code></td> + <td>Returns a one in each bit position for which the corresponding bits of either or both operands are ones.</td> + </tr> + <tr> + <td>Bitwise XOR</td> + <td><code>a ^ b</code></td> + <td>Returns a one in each bit position for which the corresponding bits of either but not both operands are ones.</td> + </tr> + <tr> + <td>Bitwise NOT</td> + <td><code>~ a</code></td> + <td>Inverts the bits of its operand.</td> + </tr> + <tr> + <td>Left shift</td> + <td><code>a << b</code></td> + <td>Shifts <code>a</code> in binary representation <code>b</code> bits to the left, shifting in zeros from the right.</td> + </tr> + <tr> + <td>Sign-propagating right shift</td> + <td><code>a >> b</code></td> + <td>Shifts <code>a</code> in binary representation <code>b</code> bits to the right, discarding bits shifted off.</td> + </tr> + <tr> + <td>Zero-fill right shift</td> + <td><code>a >>> b</code></td> + <td>Shifts <code>a</code> in binary representation <code>b</code> bits to the right, discarding bits shifted off, and shifting in zeros from the left.</td> + </tr> + </tbody> +</table> + +<h4 id="Bitwise_Logical_Operators" name="Bitwise_Logical_Operators">Bitwise logical operators</h4> + +<p>Conceptually, the bitwise logical operators work as follows:</p> + +<ul> + <li>The operands are converted to thirty-two-bit integers and expressed by a series of bits (zeros and ones).</li> + <li>Each bit in the first operand is paired with the corresponding bit in the second operand: first bit to first bit, second bit to second bit, and so on.</li> + <li>The operator is applied to each pair of bits, and the result is constructed bitwise.</li> +</ul> + +<p>For example, the binary representation of nine is 1001, and the binary representation of fifteen is 1111. So, when the bitwise operators are applied to these values, the results are as follows:</p> + +<table class="standard-table"> + <caption>Table 3.5 Bitwise operator examples</caption> + <thead> + <tr> + <th scope="col">Expression</th> + <th scope="col">Result</th> + <th scope="col">Binary Description</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>15 & 9</code></td> + <td><code>9</code></td> + <td><code>1111 & 1001 = 1001</code></td> + </tr> + <tr> + <td><code>15 | 9</code></td> + <td><code>15</code></td> + <td><code>1111 | 1001 = 1111</code></td> + </tr> + <tr> + <td><code>15 ^ 9</code></td> + <td><code>6</code></td> + <td><code>1111 ^ 1001 = 0110</code></td> + </tr> + <tr> + <td><code>~15</code></td> + <td><code>0</code></td> + <td><code>~1111 = 0000</code></td> + </tr> + <tr> + <td><code>~9</code></td> + <td><code>6</code></td> + <td><code>~1001 = 0110</code></td> + </tr> + </tbody> +</table> + +<p> </p> + +<h4 id="Bitwise_Shift_Operators" name="Bitwise_Shift_Operators">Bitwise shift operators</h4> + +<p>The bitwise shift operators take two operands: the first is a quantity to be shifted, and the second specifies the number of bit positions by which the first operand is to be shifted. The direction of the shift operation is controlled by the operator used.</p> + +<p>Shift operators convert their operands to thirty-two-bit integers and return a result of the same type as the left operand.</p> + +<p>The shift operators are listed in the following table.</p> + +<table class="fullwidth-table"> + <caption>Table 3.6 Bitwise shift operators</caption> + <thead> + <tr> + <th scope="col">Operator</th> + <th scope="col">Description</th> + <th scope="col">Example</th> + </tr> + </thead> + <tbody> + <tr> + <td><code><<</code><br> + (Left shift)</td> + <td>This operator shifts the first operand the specified number of bits to the left. Excess bits shifted off to the left are discarded. Zero bits are shifted in from the right.</td> + <td><code>9<<2</code> yields 36, because 1001 shifted 2 bits to the left becomes 100100, which is 36.</td> + </tr> + <tr> + <td><code>>></code><br> + (Sign-propagating right shift)</td> + <td>This operator shifts the first operand the specified number of bits to the right. Excess bits shifted off to the right are discarded. Copies of the leftmost bit are shifted in from the left.</td> + <td><code>9>>2</code> yields 2, because 1001 shifted 2 bits to the right becomes 10, which is 2. Likewise, <code>-9>>2</code> yields -3, because the sign is preserved.</td> + </tr> + <tr> + <td><code>>>></code><br> + (Zero-fill right shift)</td> + <td>This operator shifts the first operand the specified number of bits to the right. Excess bits shifted off to the right are discarded. Zero bits are shifted in from the left.</td> + <td><code>19>>>2</code> yields 4, because 10011 shifted 2 bits to the right becomes 100, which is 4. For non-negative numbers, zero-fill right shift and sign-propagating right shift yield the same result.</td> + </tr> + </tbody> +</table> + +<h3 id="Logical_operators">Logical operators</h3> + +<p>Logical operators are typically used with Boolean (logical) values; when they are, they return a Boolean value. However, the && and || operators actually return the value of one of the specified operands, so if these operators are used with non-Boolean values, they may return a non-Boolean value. The logical operators are described in the following table.</p> + +<table class="fullwidth-table"> + <caption>Table 3.6 Logical operators</caption> + <thead> + <tr> + <th scope="col">Operator</th> + <th scope="col">Usage</th> + <th scope="col">Description</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>&&</code></td> + <td><code>expr1 && expr2</code></td> + <td>(Logical AND) Returns <code>expr1</code> if it can be converted to false; otherwise, returns <code>expr2</code>. Thus, when used with Boolean values, <code>&&</code> returns true if both operands are true; otherwise, returns false.</td> + </tr> + <tr> + <td><code>||</code></td> + <td><code>expr1 || expr2</code></td> + <td>(Logical OR) Returns <code>expr1</code> if it can be converted to true; otherwise, returns <code>expr2</code>. Thus, when used with Boolean values, <code>||</code> returns true if either operand is true; if both are false, returns false.</td> + </tr> + <tr> + <td><code>!</code></td> + <td><code>!expr</code></td> + <td>(Logical NOT) Returns false if its single operand can be converted to true; otherwise, returns true.</td> + </tr> + </tbody> +</table> + +<p>Examples of expressions that can be converted to false are those that evaluate to null, 0, the empty string (""), or undefined.</p> + +<p>The following code shows examples of the && (logical AND) operator.</p> + +<pre class="brush: js">var a1 = true && true; // t && t returns true +var a2 = true && false; // t && f returns false +var a3 = false && true; // f && t returns false +var a4 = false && (3 == 4); // f && f returns false +var a5 = "Cat" && "Dog"; // t && t returns Dog +var a6 = false && "Cat"; // f && t returns false +var a7 = "Cat" && false; // t && f returns false +</pre> + +<p>The following code shows examples of the || (logical OR) operator.</p> + +<pre class="brush: js">var o1 = true || true; // t || t returns true +var o2 = false || true; // f || t returns true +var o3 = true || false; // t || f returns true +var o4 = false || (3 == 4); // f || f returns false +var o5 = "Cat" || "Dog"; // t || t returns Cat +var o6 = false || "Cat"; // f || t returns Cat +var o7 = "Cat" || false; // t || f returns Cat +</pre> + +<p>The following code shows examples of the ! (logical NOT) operator.</p> + +<pre class="brush: js">var n1 = !true; // !t returns false +var n2 = !false; // !f returns true +var n3 = !"Cat"; // !t returns false +</pre> + +<h4 id="Short-Circuit_Evaluation" name="Short-Circuit_Evaluation">Short-circuit evaluation</h4> + +<p>As logical expressions are evaluated left to right, they are tested for possible "short-circuit" evaluation using the following rules:</p> + +<ul> + <li><code>false</code> && <em>anything</em> is short-circuit evaluated to false.</li> + <li><code>true</code> || <em>anything</em> is short-circuit evaluated to true.</li> +</ul> + +<p>The rules of logic guarantee that these evaluations are always correct. Note that the <em>anything</em> part of the above expressions is not evaluated, so any side effects of doing so do not take effect.</p> + +<h3 id="String_operators">String operators</h3> + +<p>In addition to the comparison operators, which can be used on string values, the concatenation operator (+) concatenates two string values together, returning another string that is the union of the two operand strings. For example, <code>"my " + "string"</code> returns the string <code>"my string"</code>.</p> + +<p>The shorthand assignment operator += can also be used to concatenate strings. For example, if the variable <code>mystring</code> has the value "alpha", then the expression <code>mystring += "bet"</code> evaluates to "alphabet" and assigns this value to <code>mystring</code>.</p> + +<h3 id="Special_operators">Special operators</h3> + +<p>JavaScript provides the following special operators:</p> + +<ul> + <li>{{ web.link("#Conditional_operator", "Conditional operator") }}</li> + <li>{{ web.link("#Comma_operator", "Comma operator") }}</li> + <li><code>{{ web.link("#delete", "delete") }}</code></li> + <li><code>{{ web.link("#in", "in") }}</code></li> + <li><code>{{ web.link("#instanceof", "instanceof") }}</code></li> + <li><code>{{ web.link("#new", "new") }}</code></li> + <li><code>{{ web.link("#this", "this") }}</code></li> + <li><code>{{ web.link("#typeof", "typeof") }}</code></li> + <li><code>{{ web.link("#void", "void") }}</code></li> +</ul> + +<h4 id="conditional_operator" name="conditional_operator">Conditional operator</h4> + +<p>The conditional operator is the only JavaScript operator that takes three operands. The operator can have one of two values based on a condition. The syntax is:</p> + +<pre><em>condition</em> ? <em>val1</em> : <em>val2</em> +</pre> + +<p>If <code>condition</code> is true, the operator has the value of <code>val1</code>. Otherwise it has the value of <code>val2</code>. You can use the conditional operator anywhere you would use a standard operator.</p> + +<p>For example,</p> + +<pre class="brush: js">var status = (age >= 18) ? "adult" : "minor"; +</pre> + +<p>This statement assigns the value "adult" to the variable <code>status</code> if <code>age</code> is eighteen or more. Otherwise, it assigns the value "minor" to <code>status</code>.</p> + +<h4 id="comma_operator" name="comma_operator">Comma operator</h4> + +<p>The comma operator (<code>,</code>) simply evaluates both of its operands and returns the value of the second operand. This operator is primarily used inside a <code>for</code> loop, to allow multiple variables to be updated each time through the loop.</p> + +<p>For example, if <code>a</code> is a 2-dimensional array with 10 elements on a side, the following code uses the comma operator to increment two variables at once. The code prints the values of the diagonal elements in the array:</p> + +<pre class="brush: js">for (var i = 0, j = 9; i <= 9; i++, j--) + document.writeln("a[" + i + "][" + j + "]= " + a[i][j]); +</pre> + +<h4 id="delete" name="delete"><code>delete</code></h4> + +<p>The <code>delete</code> operator deletes an object, an object's property, or an element at a specified index in an array. The syntax is:</p> + +<pre class="brush: js">delete objectName; +delete objectName.property; +delete objectName[index]; +delete property; // legal only within a with statement +</pre> + +<p>where <code>objectName</code> is the name of an object, <code>property</code> is an existing property, and <code>index</code> is an integer representing the location of an element in an array.</p> + +<p>The fourth form is legal only within a <code>with</code> statement, to delete a property from an object.</p> + +<p>You can use the <code>delete</code> operator to delete variables declared implicitly but not those declared with the <code>var</code> statement.</p> + +<p>If the <code>delete</code> operator succeeds, it sets the property or element to <code>undefined</code>. The <code>delete</code> operator returns true if the operation is possible; it returns false if the operation is not possible.</p> + +<pre class="brush: js">x = 42; +var y = 43; +myobj = new Number(); +myobj.h = 4; // create property h +delete x; // returns true (can delete if declared implicitly) +delete y; // returns false (cannot delete if declared with var) +delete Math.PI; // returns false (cannot delete predefined properties) +delete myobj.h; // returns true (can delete user-defined properties) +delete myobj; // returns true (can delete if declared implicitly) +</pre> + +<h5 id="Deleting_array_elements">Deleting array elements</h5> + +<p>When you delete an array element, the array length is not affected. For example, if you delete <code>a[3]</code>, <code>a[4]</code> is still <code>a[4]</code> and <code>a[3]</code> is undefined.</p> + +<p>When the <code>delete</code> operator removes an array element, that element is no longer in the array. In the following example, <code>trees[3]</code> is removed with <code>delete</code>. However, <code>trees[3]</code> is still addressable and returns <code>undefined</code>.</p> + +<pre class="brush: js">var trees = new Array("redwood", "bay", "cedar", "oak", "maple"); +delete trees[3]; +if (3 in trees) { + // this does not get executed +} +</pre> + +<p>If you want an array element to exist but have an undefined value, use the <code>undefined</code> keyword instead of the <code>delete</code> operator. In the following example, <code>trees[3]</code> is assigned the value <code>undefined</code>, but the array element still exists:</p> + +<pre class="brush: js">var trees = new Array("redwood", "bay", "cedar", "oak", "maple"); +trees[3] = undefined; +if (3 in trees) { + // this gets executed +} +</pre> + +<h4 id="in" name="in"><code>in</code></h4> + +<p>The <code>in</code> operator returns true if the specified property is in the specified object. The syntax is:</p> + +<pre class="brush: js">propNameOrNumber in objectName +</pre> + +<p>where <code>propNameOrNumber</code> is a string or numeric expression representing a property name or array index, and <code>objectName</code> is the name of an object.</p> + +<p>The following examples show some uses of the <code>in</code> operator.</p> + +<pre class="brush: js">// Arrays +var trees = new Array("redwood", "bay", "cedar", "oak", "maple"); +0 in trees; // returns true +3 in trees; // returns true +6 in trees; // returns false +"bay" in trees; // returns false (you must specify the index number, + // not the value at that index) +"length" in trees; // returns true (length is an Array property) + +// Predefined objects +"PI" in Math; // returns true +var myString = new String("coral"); +"length" in myString; // returns true + +// Custom objects +var mycar = {make: "Honda", model: "Accord", year: 1998}; +"make" in mycar; // returns true +"model" in mycar; // returns true +</pre> + +<h4 id="instanceof" name="instanceof"><code>instanceof</code></h4> + +<p>The <code>instanceof</code> operator returns true if the specified object is of the specified object type. The syntax is:</p> + +<pre class="brush: js">objectName instanceof objectType +</pre> + +<p>where <code>objectName</code> is the name of the object to compare to <code>objectType</code>, and <code>objectType</code> is an object type, such as <code>Date</code> or <code>Array</code>.</p> + +<p>Use <code>instanceof</code> when you need to confirm the type of an object at runtime. For example, when catching exceptions, you can branch to different exception-handling code depending on the type of exception thrown.</p> + +<p>For example, the following code uses <code>instanceof</code> to determine whether <code>theDay</code> is a <code>Date</code> object. Because <code>theDay</code> is a <code>Date</code> object, the statements in the <code>if</code> statement execute.</p> + +<pre class="brush: js">var theDay = new Date(1995, 12, 17); +if (theDay instanceof Date) { + // statements to execute +} +</pre> + +<h4 id="new" name="new"><code>new</code></h4> + +<p>You can use the <code>new</code> operator to create an instance of a user-defined object type or of one of the predefined object types <code>Array</code>, <code>Boolean</code>, <code>Date</code>, <code>Function</code>, <code>Image</code>, <code>Number</code>, <code>Object</code>, <code>Option</code>, <code>RegExp</code>, or <code>String</code>. On the server, you can also use it with <code>DbPool</code>, <code>Lock</code>, <code>File</code>, or <code>SendMail</code>. Use <code>new</code> as follows:</p> + +<pre class="brush: js">var objectName = new objectType([param1, param2, ..., paramN]); +</pre> + +<p>You can also create objects using object initializers, as described in {{ web.link("Working_with_objects#Using_object_initializers", "using object initializers") }}.</p> + +<p>See the <a href="/en-US/docs/JavaScript/Reference/Operators/new" title="en-US/docs/JavaScript/Reference/Operators/Special_Operators/new_Operator"><code>new</code> operator</a> page in the Core JavaScript Reference for more information.</p> + +<h4 id="this" name="this"><code>this</code></h4> + +<p>Use the <code>this</code> keyword to refer to the current object. In general, <code>this</code> refers to the calling object in a method. Use <code>this</code> as follows:</p> + +<pre class="brush: js">this["propertyName"] +</pre> + +<pre class="brush: js">this.propertyName +</pre> + +<p><strong>Example 1.</strong><br> + Suppose a function called <code>validate</code> validates an object's <code>value</code> property, given the object and the high and low values:</p> + +<pre class="brush: js">function validate(obj, lowval, hival){ + if ((obj.value < lowval) || (obj.value > hival)) + alert("Invalid Value!"); +} +</pre> + +<p>You could call <code>validate</code> in each form element's <code>onChange</code> event handler, using <code>this</code> to pass it the form element, as in the following example:</p> + +<pre class="brush: html"><B>Enter a number between 18 and 99:</B> +<INPUT TYPE="text" NAME="age" SIZE=3 + onChange="validate(this, 18, 99);"> +</pre> + +<p><strong>Example 2.</strong><br> + When combined with the <code>form</code> property, <code>this</code> can refer to the current object's parent form. In the following example, the form <code>myForm</code> contains a <code>Text</code> object and a button. When the user clicks the button, the value of the <code>Text</code> object is set to the form's name. The button's <code>onClick</code> event handler uses <code>this.form</code> to refer to the parent form, <code>myForm</code>.</p> + +<pre class="brush: html"><FORM NAME="myForm"> +Form name:<INPUT TYPE="text" NAME="text1" VALUE="Beluga"> +<P> +<INPUT NAME="button1" TYPE="button" VALUE="Show Form Name" + onClick="this.form.text1.value = this.form.name;"> +</FORM> +</pre> + +<h4 id="typeof" name="typeof"><code>typeof</code></h4> + +<p>The <code>typeof</code> operator is used in either of the following ways:</p> + +<ol> + <li> + <pre class="brush: js">typeof operand +</pre> + </li> + <li> + <pre class="brush: js">typeof (operand) +</pre> + </li> +</ol> + +<p>The <code>typeof</code> operator returns a string indicating the type of the unevaluated operand. <code>operand</code> is the string, variable, keyword, or object for which the type is to be returned. The parentheses are optional.</p> + +<p>Suppose you define the following variables:</p> + +<pre class="brush: js">var myFun = new Function("5 + 2"); +var shape = "round"; +var size = 1; +var today = new Date(); +</pre> + +<p>The <code>typeof</code> operator returns the following results for these variables:</p> + +<pre class="brush: js">typeof myFun; // returns "function" +typeof shape; // returns "string" +typeof size; // returns "number" +typeof today; // returns "object" +typeof dontExist; // returns "undefined" +</pre> + +<p>For the keywords <code>true</code> and <code>null</code>, the <code>typeof</code> operator returns the following results:</p> + +<pre class="brush: js">typeof true; // returns "boolean" +typeof null; // returns "object" +</pre> + +<p>For a number or string, the <code>typeof</code> operator returns the following results:</p> + +<pre class="brush: js">typeof 62; // returns "number" +typeof 'Hello world'; // returns "string" +</pre> + +<p>For property values, the <code>typeof</code> operator returns the type of value the property contains:</p> + +<pre class="brush: js">typeof document.lastModified; // returns "string" +typeof window.length; // returns "number" +typeof Math.LN2; // returns "number" +</pre> + +<p>For methods and functions, the <code>typeof</code> operator returns results as follows:</p> + +<pre class="brush: js">typeof blur; // returns "function" +typeof eval; // returns "function" +typeof parseInt; // returns "function" +typeof shape.split; // returns "function" +</pre> + +<p>For predefined objects, the <code>typeof</code> operator returns results as follows:</p> + +<pre class="brush: js">typeof Date; // returns "function" +typeof Function; // returns "function" +typeof Math; // returns "object" +typeof Option; // returns "function" +typeof String; // returns "function" +</pre> + +<h4 id="void" name="void"><code>void</code></h4> + +<p>The <code>void</code> operator is used in either of the following ways:</p> + +<ol> + <li> + <pre class="brush: js">void (expression) +</pre> + </li> + <li> + <pre class="brush: js">void expression +</pre> + </li> +</ol> + +<p>The <code>void</code> operator specifies an expression to be evaluated without returning a value. <code>expression</code> is a JavaScript expression to evaluate. The parentheses surrounding the expression are optional, but it is good style to use them.</p> + +<p>You can use the <code>void</code> operator to specify an expression as a hypertext link. The expression is evaluated but is not loaded in place of the current document.</p> + +<p>The following code creates a hypertext link that does nothing when the user clicks it. When the user clicks the link, <code>void(0)</code> evaluates to undefined, which has no effect in JavaScript.</p> + +<pre class="brush: html"><A HREF="javascript:void(0)">Click here to do nothing</A> +</pre> + +<p>The following code creates a hypertext link that submits a form when the user clicks it.</p> + +<pre class="brush: html"><A HREF="javascript:void(document.form.submit())"> +Click here to submit</A></pre> + +<h3 id="Operator_precedence">Operator precedence</h3> + +<p>The <em>precedence</em> of operators determines the order they are applied when evaluating an expression. You can override operator precedence by using parentheses.</p> + +<p>The following table describes the precedence of operators, from highest to lowest.</p> + +<p><small><em>In accordance with <a href="/en-US/docs/Talk:JavaScript/Guide/Obsolete_Pages/Operators#Precedence_Tablerators#Precedence_Table" title="Talk:JavaScript/Guide/Obsolete_Pages/Operators#Precedence_Table">relevant discussion</a>, this table was reversed to list operators in <strong>decreasing</strong> order of priority.</em></small></p> + +<table class="standard-table"> + <caption>Table 3.7 Operator precedence</caption> + <thead> + <tr> + <th scope="col">Operator type</th> + <th scope="col">Individual operators</th> + </tr> + </thead> + <tbody> + <tr> + <td>member</td> + <td><code>. []</code></td> + </tr> + <tr> + <td>call / create instance</td> + <td><code>() new</code></td> + </tr> + <tr> + <td>negation/increment</td> + <td><code>! ~ - + ++ -- typeof void delete</code></td> + </tr> + <tr> + <td>multiply/divide</td> + <td><code>* / %</code></td> + </tr> + <tr> + <td>addition/subtraction</td> + <td><code>+ -</code></td> + </tr> + <tr> + <td>bitwise shift</td> + <td><code><< >> >>></code></td> + </tr> + <tr> + <td>relational</td> + <td><code>< <= > >= in instanceof</code></td> + </tr> + <tr> + <td>equality</td> + <td><code>== != === !==</code></td> + </tr> + <tr> + <td>bitwise-and</td> + <td><code>&</code></td> + </tr> + <tr> + <td>bitwise-xor</td> + <td><code>^</code></td> + </tr> + <tr> + <td>bitwise-or</td> + <td><code>|</code></td> + </tr> + <tr> + <td>logical-and</td> + <td><code>&&</code></td> + </tr> + <tr> + <td>logical-or</td> + <td><code>||</code></td> + </tr> + <tr> + <td>conditional</td> + <td><code>?:</code></td> + </tr> + <tr> + <td>assignment</td> + <td><code>= += -= *= /= %= <<= >>= >>>= &= ^= |=</code></td> + </tr> + <tr> + <td>comma</td> + <td><code>,</code></td> + </tr> + </tbody> +</table> + +<p>A more detailed version of this table, complete with links to additional details about each operator, may be found in <a href="/en-US/docs/JavaScript/Reference/Operators/Operator_Precedence#Table" title="en-US/docs/JavaScript/Reference/Operators/Operator_Precedence#Table">JavaScript Reference</a>.</p> diff --git a/files/pt-pt/web/javascript/guia/gramática_e_tipos/index.html b/files/pt-pt/web/javascript/guia/gramática_e_tipos/index.html new file mode 100644 index 0000000000..109bd99fe4 --- /dev/null +++ b/files/pt-pt/web/javascript/guia/gramática_e_tipos/index.html @@ -0,0 +1,641 @@ +--- +title: Gramática e tipos +slug: Web/JavaScript/Guia/Gramática_e_tipos +tags: + - Guia(2) + - JavaScript +translation_of: Web/JavaScript/Guide/Grammar_and_types +--- +<div>{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Introduction", "Web/JavaScript/Guide/Control_flow_and_error_handling")}}</div> + +<p class="summary">Este capítulo discute a gramática básica do JavaScript, declarações de variáveis, tipos de dados e literais.</p> + +<h2 id="Básicos">Básicos</h2> + +<p>JavaScript borrows most of its syntax from Java, but is also influenced by Awk, Perl and Python.</p> + +<p>JavaScript is <strong>case-sensitive</strong> and uses the <strong>Unicode</strong> character set.</p> + +<p>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 (<a href="/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Automatic_semicolon_insertion">ASI</a>) 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 <a href="/en-US/docs/Web/JavaScript/Reference/Lexical_grammar">lexical grammar</a>.</p> + +<h2 id="Comentários">Comentários</h2> + +<p>The syntax of <strong>comments</strong> is the same as in C++ and in many other languages:</p> + +<pre class="brush: js">// a one line comment + +/* this is a longer, + multi-line comment + */ + +/* You can't, however, /* nest comments */ SyntaxError */</pre> + +<h2 id="Declarações">Declarações</h2> + +<p>There are three kinds of declarations in JavaScript.</p> + +<dl> + <dt>{{jsxref("Statements/var", "var")}}</dt> + <dd>Declares a variable, optionally initializing it to a value.</dd> + <dt>{{experimental_inline}} {{jsxref("Statements/let", "let")}}</dt> + <dd>Declares a block scope local variable, optionally initializing it to a value.</dd> + <dt>{{experimental_inline}} {{jsxref("Statements/const", "const")}}</dt> + <dd>Declares a read-only named constant.</dd> +</dl> + +<h3 id="Variáveis">Variáveis</h3> + +<p>You use variables as symbolic names for values in your application. The names of variables, called {{Glossary("Identifier", "identifiers")}}, conform to certain rules.</p> + +<p>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).</p> + +<p>You can use ISO 8859-1 or Unicode letters such as å and ü in identifiers. You can also use the <a href="/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#String_literals">Unicode escape sequences</a> as characters in identifiers.</p> + +<p>Some examples of legal names are <code>Number_hits</code>, <code>temp99</code>, and <code>_name</code>.</p> + +<h3 id="Declararação_de_variáveis">Declararação de variáveis</h3> + +<p>You can declare a variable in three ways:</p> + +<ul> + <li>With the keyword {{jsxref("Statements/var", "var")}}. For example, <code>var x = 42</code>. This syntax can be used to declare both local and global variables.</li> + <li>By simply assigning it a value. For example, <code>x = 42</code>. This always declares a global variable. It generates a strict JavaScript warning. You shouldn't use this variant.</li> + <li>With the keyword {{jsxref("Statements/let", "let")}}. For example, <code>let y = 13</code>. This syntax can be used to declare a block scope local variable. See <a href="#Variable_scope">Variable scope</a> below.</li> +</ul> + +<h3 id="Avaliação_de_variáveis">Avaliação de variáveis</h3> + +<p>A variable declared using the <code>var</code> statement with no initial value specified has the value {{jsxref("undefined")}}.</p> + +<p>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:</p> + +<pre class="brush: js">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; </pre> + +<p>You can use <code>undefined</code> to determine whether a variable has a value. In the following code, the variable <code>input</code> is not assigned a value, and the <code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/if...else" title="en-US/docs/JavaScript/Reference/Statements/if...else">if</a></code> statement evaluates to <code>true</code>.</p> + +<pre class="brush: js">var input; +if(input === undefined){ + doThis(); +} else { + doThat(); +} +</pre> + +<p>The <code>undefined</code> value behaves as <code>false</code> when used in a boolean context. For example, the following code executes the function <code>myFunction</code> because the <code>myArray</code> element is undefined:</p> + +<pre class="brush: js">var myArray = []; +if (!myArray[0]) myFunction(); +</pre> + +<p>The <code>undefined</code> value converts to <code>NaN</code> when used in numeric context.</p> + +<pre class="brush: js">var a; +a + 2; // Evaluates to NaN</pre> + +<p>When you evaluate a {{jsxref("null")}} variable, the null value behaves as 0 in numeric contexts and as false in boolean contexts. For example:</p> + +<pre class="brush: js">var n = null; +console.log(n * 32); // Will log 0 to the console +</pre> + +<h3 id="Variable_scope">Variable scope</h3> + +<p>When you declare a variable outside of any function, it is called a <em>global</em> 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 <em>local</em> variable, because it is available only within that function.</p> + +<p>JavaScript before ECMAScript 2015 does not have <a href="/en-US/docs/Web/JavaScript/Guide/Control_flow_and_error_handling#Block_statement" title="en-US/docs/Web/JavaScript/Guide/Control_flow_and_error_handling#Block_statement">block statement</a> scope; rather, a variable declared within a block is local to the <em>function (or global scope)</em> that the block resides within. For example the following code will log <code>5</code>, because the scope of <code>x</code> is the function (or global context) within which <code>x</code> is declared, not the block, which in this case is an <code>if</code> statement.</p> + +<pre class="brush: js">if (true) { + var x = 5; +} +console.log(x); // 5 +</pre> + +<p>This behavior changes, when using the <code>let</code> declaration introduced in ECMAScript 2015.</p> + +<pre class="brush: js">if (true) { + let y = 5; +} +console.log(y); // ReferenceError: y is not defined +</pre> + +<h3 id="Variable_hoisting">Variable hoisting</h3> + +<p>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 <strong>hoisting</strong>; 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 <code>undefined</code>. So even if you declare and initialize after you use or refer to this variable, it will still return undefined.</p> + +<pre class="brush: js">/** + * 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"; +})(); +</pre> + +<p>The above examples will be interpreted the same as:</p> + +<pre class="brush: js">/** + * 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"; +})(); +</pre> + +<p>Because of hoisting, all <code>var</code> 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.</p> + +<p>In ECMAScript 2015, <code>let (const)</code> <strong>will not hoist</strong> the variable to the top of the block. However, referencing the variable in the block before the variable declaration results in a <code><a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/ReferenceError" title="TypeError">ReferenceError</a>.</code> The variable is in a "temporal dead zone" from the start of the block until the declaration is processed.</p> + +<pre class="brush: js">console.log(x); // <code>ReferenceError</code> +let x = 3;</pre> + +<h3 id="Variáveis_gGlobais">Variáveis gGlobais</h3> + +<p>Global variables are in fact properties of the <em>global object</em>. In web pages the global object is {{domxref("window")}}, so you can set and access global variables using the <code>window.<em>variable</em></code> syntax.</p> + +<p>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 <code>phoneNumber</code> is declared in a document, you can refer to this variable from an iframe as <code>parent.phoneNumber</code>.</p> + +<h3 id="Constantes">Constantes</h3> + +<p>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.</p> + +<pre class="brush: js">const PI = 3.14; +</pre> + +<p>A constant cannot change value through assignment or be re-declared while the script is running. It has to be initialized to a value.</p> + +<p>The scope rules for constants are the same as those for <code>let</code> block scope variables. If the <code>const</code> keyword is omitted, the identifier is assumed to represent a variable.</p> + +<p>You cannot declare a constant with the same name as a function or variable in the same scope. For example:</p> + +<pre class="brush: js">// THIS WILL CAUSE AN ERROR +function f() {}; +const f = 5; + +// THIS WILL CAUSE AN ERROR ALSO +function f() { + const g = 5; + var g; + + //statements +} +</pre> + +<p>However, object attributes are not protected, so the following statement is executed without problems.</p> + +<pre class="brush: js"><code>const MY_OBJECT = {"key": "value"}; +MY_OBJECT.key = "otherValue";</code></pre> + +<h2 id="Estruturas_e_tipode_dados">Estruturas e tipode dados</h2> + +<h3 id="tipos_de_dados">tipos de dados</h3> + +<p>The latest ECMAScript standard defines seven data types:</p> + +<ul> + <li>Six data types that are {{Glossary("Primitive", "primitives")}}: + <ul> + <li>{{Glossary("Boolean")}}. <code>true</code> and <code>false</code>.</li> + <li>{{Glossary("null")}}. A special keyword denoting a null value. Because JavaScript is case-sensitive, <code>null</code> is not the same as <code>Null</code>, <code>NULL</code>, or any other variant.</li> + <li>{{Glossary("undefined")}}. A top-level property whose value is undefined.</li> + <li>{{Glossary("Number")}}. <code>42</code> or <code>3.14159</code>.</li> + <li>{{Glossary("String")}}. "Howdy"</li> + <li>{{Glossary("Symbol")}} (new in ECMAScript 2015). A data type whose instances are unique and immutable.</li> + </ul> + </li> + <li>and {{Glossary("Object")}}</li> +</ul> + +<p>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.</p> + +<h3 id="Conversão_de_tipo_de_dados">Conversão de tipo de dados</h3> + +<p>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:</p> + +<pre class="brush: js">var answer = 42; +</pre> + +<p>And later, you could assign the same variable a string value, for example:</p> + +<pre class="brush: js">answer = "Thanks for all the fish..."; +</pre> + +<p>Because JavaScript is dynamically typed, this assignment does not cause an error message.</p> + +<p>In expressions involving numeric and string values with the + operator, JavaScript converts numeric values to strings. For example, consider the following statements:</p> + +<pre class="brush: js">x = "The answer is " + 42 // "The answer is 42" +y = 42 + " is the answer" // "42 is the answer" +</pre> + +<p>In statements involving other operators, JavaScript does not convert numeric values to strings. For example:</p> + +<pre class="brush: js">"37" - 7 // 30 +"37" + 7 // "377" +</pre> + +<h3 id="Conversão_de_strings_para_números">Conversão de strings para números</h3> + +<p>In the case that a value representing a number is in memory as a string, there are methods for conversion.</p> + +<ul> + <li id="parseInt()_and_parseFloat()">{{jsxref("parseInt", "parseInt()")}}</li> + <li>{{jsxref("parseFloat", "parseFloat()")}}</li> +</ul> + +<p><code>parseInt</code> will only return whole numbers, so its use is diminished for decimals. Additionally, a best practice for <code>parseInt</code> is to always include the radix parameter. The radix parameter is used to specify which numerical system is to be used.</p> + +<p>An alternative method of retrieving a number from a string is with the <code>+</code> (unary plus) operator:</p> + +<pre class="brush: js">"1.1" + "1.1" = "1.11.1" +(+"1.1") + (+"1.1") = 2.2 +// Note: the parentheses are added for clarity, not required.</pre> + +<h2 id="Literais">Literais</h2> + +<p>You use literals to represent values in JavaScript. These are fixed values, not variables, that you <em>literally</em> provide in your script. This section describes the following types of literals:</p> + +<ul> + <li>{{anch("Array literals")}}</li> + <li>{{anch("Boolean literals")}}</li> + <li>{{anch("Floating-point literals")}}</li> + <li>{{anch("Integers")}}</li> + <li>{{anch("Object literals")}}</li> + <li>{{anch("RegExp literals")}}</li> + <li>{{anch("String literals")}}</li> +</ul> + +<h3 id="Literais_de_tabela">Literais de tabela</h3> + +<p>An array literal is a list of zero or more expressions, each of which represents an array element, enclosed in square brackets (<code>[]</code>). 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.</p> + +<p>The following example creates the <code>coffees</code> array with three elements and a length of three:</p> + +<pre class="brush: js">var coffees = ["French Roast", "Colombian", "Kona"]; +</pre> + +<div class="note"> +<p><strong>Note :</strong> An array literal is a type of object initializer. See <a href="/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#Using_object_initializers" title="en-US/docs/JavaScript/Guide/Working with Objects#Using Object Initializers">Using Object Initializers</a>.</p> +</div> + +<p>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.</p> + +<p>Array literals are also <code>Array</code> objects. See {{jsxref("Array")}} and <a href="/en-US/docs/Web/JavaScript/Guide/Indexed_collections">Indexed collections</a> for details on <code>Array</code> objects.</p> + +<h4 id="Extra_commas_in_array_literals">Extra commas in array literals</h4> + +<p>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 <code>undefined</code> for the unspecified elements. The following example creates the <code>fish</code> array:</p> + +<pre class="brush: js">var fish = ["Lion", , "Angel"]; +</pre> + +<p>This array has two elements with values and one empty element (<code>fish[0]</code> is "Lion", <code>fish[1]</code> is <code>undefined</code>, and <code>fish[2]</code> is "Angel").</p> + +<p>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 <code>myList[3]</code>. All other commas in the list indicate a new element.</p> + +<div class="note"> +<p><strong>Nota :</strong> Trailing commas can create errors in older browser versions and it is a best practice to remove them.</p> +</div> + +<pre class="brush: js">var myList = ['home', , 'school', ]; +</pre> + +<p>In the following example, the length of the array is four, and <code>myList[0]</code> and <code>myList[2]</code> are missing.</p> + +<pre class="brush: js">var myList = [ , 'home', , 'school']; +</pre> + +<p>In the following example, the length of the array is four, and <code>myList[1]</code> and <code>myList[3]</code> are missing. Only the last comma is ignored.</p> + +<pre class="brush: js">var myList = ['home', , 'school', , ]; +</pre> + +<p>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 <code>undefined</code> will increase your code's clarity and maintainability.</p> + +<h3 id="Lietrais_boolianas">Lietrais boolianas</h3> + +<p>The Boolean type has two literal values: <code>true</code> and <code>false</code>.</p> + +<p>Do not confuse the primitive Boolean values <code>true</code> and <code>false</code> 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.</p> + +<h3 id="Íntegros">Íntegros</h3> + +<p>Integers can be expressed in decimal (base 10), hexadecimal (base 16), octal (base 8) and binary (base 2).</p> + +<ul> + <li>Decimal integer literal consists of a sequence of digits without a leading 0 (zero).</li> + <li>Leading 0 (zero) on an integer literal, or leading 0o (or 0O) indicates it is in octal. Octal integers can include only the digits 0-7.</li> + <li>Leading 0x (or 0X) indicates hexadecimal. Hexadecimal integers can include digits (0-9) and the letters a-f and A-F.</li> + <li> + <p>Leading 0b (or 0B) indicates binary. Binary integers can include digits only 0 and 1.</p> + </li> +</ul> + +<p>Some examples of integer literals are:</p> + +<pre class="eval">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) +</pre> + +<p>For more information, see <a href="/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Numeric_literals">Numeric literals in the Lexical grammar reference</a>.</p> + +<h3 id="Literais_de_ponto_flutuante">Literais de ponto flutuante</h3> + +<p>A floating-point literal can have the following parts:</p> + +<ul> + <li>A decimal integer which can be signed (preceded by "+" or "-"),</li> + <li>A decimal point ("."),</li> + <li>A fraction (another decimal number),</li> + <li>An exponent.</li> +</ul> + +<p>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").</p> + +<p>More succinctly, the syntax is:</p> + +<pre class="eval">[(+|-)][digits][.digits][(E|e)[(+|-)]digits] +</pre> + +<p>For example:</p> + +<pre class="eval">3.1415926 +-.123456789 +-3.1E+12 +.1e-23 +</pre> + +<h3 id="Literais_de_objeto">Literais de objeto</h3> + +<p>An object literal is a list of zero or more pairs of property names and associated values of an object, enclosed in curly braces (<code>{}</code>). 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.</p> + +<p>The following is an example of an object literal. The first element of the <code>car</code> object defines a property, <code>myCar</code>, and assigns to it a new string, "<code>Saturn</code>"; the second element, the <code>getCar</code> property, is immediately assigned the result of invoking the function <code>(carTypes("Honda"));</code> the third element, the <code>special</code> property, uses an existing variable (<code>sales</code>).</p> + +<pre class="brush: js">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 +</pre> + +<p>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.</p> + +<pre class="brush: js">var car = { manyCars: {a: "Saab", "b": "Jeep"}, 7: "Mazda" }; + +console.log(car.manyCars.b); // Jeep +console.log(car[7]); // Mazda +</pre> + +<p>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 (<code>.</code>) property, but can be accessed and set with the array-like notation("<code>[]</code>").</p> + +<pre class="brush: js">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!</pre> + +<p>In ES2015, object literals are extended to support setting the prototype at construction, shorthand for <code>foo: foo</code> 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.</p> + +<pre class="brush: js">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 +};</pre> + +<p>Por favor, note:</p> + +<pre class="brush: js">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 +</pre> + +<h3 id="RegExp_literals">RegExp literals</h3> + +<p>A regex literal is a pattern enclosed between slashes. The following is an example of an regex literal.</p> + +<pre class="brush: js">var re = /ab+c/;</pre> + +<h3 id="Lietrais_de_string">Lietrais de string</h3> + +<p>A string literal is zero or more characters enclosed in double (<code>"</code>) or single (<code>'</code>) 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:</p> + +<pre class="brush: js">"foo" +'bar' +"1234" +"one line \n another line" +"John's cat" +</pre> + +<p>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 <code>String.length</code> property with a string literal:</p> + +<pre class="brush: js">console.log("John's cat".length) +// Will print the number of symbols in the string including whitespace. +// In this case, 10. +</pre> + +<p>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.</p> + +<pre class="brush: js">// 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);</pre> + +<p>You should use string literals unless you specifically need to use a String object. See {{jsxref("String")}} for details on <code>String</code> objects.</p> + +<h4 id="Using_special_characters_in_strings">Using special characters in strings</h4> + +<p>In addition to ordinary characters, you can also include special characters in strings, as shown in the following example.</p> + +<pre class="brush: js">"one line \n another line" +</pre> + +<p>The following table lists the special characters that you can use in JavaScript strings.</p> + +<table class="standard-table"> + <caption>Table: JavaScript special characters</caption> + <thead> + <tr> + <th scope="col">Cárater</th> + <th scope="col">Significado</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>\0</code></td> + <td>Null Byte</td> + </tr> + <tr> + <td><code>\b</code></td> + <td>Backspace</td> + </tr> + <tr> + <td><code>\f</code></td> + <td>Form feed</td> + </tr> + <tr> + <td><code>\n</code></td> + <td>New line</td> + </tr> + <tr> + <td><code>\r</code></td> + <td>Carriage return</td> + </tr> + <tr> + <td><code>\t</code></td> + <td>Tab</td> + </tr> + <tr> + <td><code>\v</code></td> + <td>Vertical tab</td> + </tr> + <tr> + <td><code>\'</code></td> + <td>Apostrophe or single quote</td> + </tr> + <tr> + <td><code>\"</code></td> + <td>Double quote</td> + </tr> + <tr> + <td><code>\\</code></td> + <td>Backslash character</td> + </tr> + <tr> + <td><code>\<em>XXX</em></code></td> + <td>The character with the Latin-1 encoding specified by up to three octal digits <em>XXX</em> between 0 and 377. For example, \251 is the octal sequence for the copyright symbol.</td> + </tr> + <tr> + </tr> + <tr> + <td><code>\x<em>XX</em></code></td> + <td>The character with the Latin-1 encoding specified by the two hexadecimal digits <em>XX</em> between 00 and FF. For example, \xA9 is the hexadecimal sequence for the copyright symbol.</td> + </tr> + <tr> + </tr> + <tr> + <td><code>\u<em>XXXX</em></code></td> + <td>The Unicode character specified by the four hexadecimal digits <em>XXXX</em>. For example, \u00A9 is the Unicode sequence for the copyright symbol. See <a href="/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#String_literals">Unicode escape sequences</a>.</td> + </tr> + <tr> + <td><code>\u<em>{XXXXX}</em></code></td> + <td>Unicode code point escapes. For example, \u{2F804} is the same as the simple Unicode escapes \uD87E\uDC04.</td> + </tr> + </tbody> +</table> + +<h4 id="Escaping_characters">Escaping characters</h4> + +<p>For characters not listed in the table, a preceding backslash is ignored, but this usage is deprecated and should be avoided.</p> + +<p>You can insert a quotation mark inside a string by preceding it with a backslash. This is known as <em>escaping</em> the quotation mark. For example:</p> + +<pre class="brush: js">var quote = "He read \"The Cremation of Sam McGee\" by R.W. Service."; +console.log(quote); +</pre> + +<p>The result of this would be:</p> + +<pre class="eval">He read "The Cremation of Sam McGee" by R.W. Service. +</pre> + +<p>To include a literal backslash inside a string, you must escape the backslash character. For example, to assign the file path <code>c:\temp</code> to a string, use the following:</p> + +<pre class="brush: js">var home = "c:\\temp"; +</pre> + +<p>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.</p> + +<pre class="brush: js">var str = "this string \ +is broken \ +across multiple\ +lines." +console.log(str); // this string is broken across multiplelines. +</pre> + +<p>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:</p> + +<pre class="brush: js">var poem = +"Roses are red,\n\ +Violets are blue.\n\ +Sugar is sweet,\n\ +and so is foo." +</pre> + +<h2 id="Mais_informação">Mais informação</h2> + +<p>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:</p> + +<ul> + <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Control_flow_and_error_handling">Control flow and error handling</a></li> + <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration">Loops and iteration</a></li> + <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions">Functions</a></li> + <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators">Expressions and operators</a></li> +</ul> + +<p>In the next chapter, we will have a look at control flow constructs and error handling.</p> + +<p>{{PreviousNext("Web/JavaScript/Guide/Introduction", "Web/JavaScript/Guide/Control_flow_and_error_handling")}}</p> diff --git a/files/pt-pt/web/javascript/guia/index.html b/files/pt-pt/web/javascript/guia/index.html new file mode 100644 index 0000000000..aec08fb7ad --- /dev/null +++ b/files/pt-pt/web/javascript/guia/index.html @@ -0,0 +1,123 @@ +--- +title: Guia de JavaScript +slug: Web/JavaScript/Guia +tags: + - Guía + - JavaScript + - 'l10n:prioridade' +translation_of: Web/JavaScript/Guide +--- +<div>{{jsSidebar("JavaScript Guide")}}</div> + +<p class="summary">The JavaScript Guide shows you how to use <a href="/en-US/docs/Web/JavaScript">JavaScript</a> and gives an overview of the language. If you want to get started with JavaScript or programming in general, consult the articles in the <a href="/en-US/Learn">learning area</a>. If you need exhaustive information about a language feature, have a look at the <a href="/en-US/docs/Web/JavaScript/Reference">JavaScript reference</a>.</p> + +<h2 id="Capítulos">Capítulos</h2> + +<p>This Guide is divided into several chapters:</p> + +<ul class="card-grid"> + <li><span><a href="/en-US/docs/Web/JavaScript/Guide/Introduction">Introdução</a></span> + + <p><a href="/pt-PT/docs/Web/JavaScript/Guia/Introdução">About this guide</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Introduction#What_is_JavaScript">About JavaScript</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Introduction#JavaScript_and_Java">JavaScript and Java</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Introduction#JavaScript_and_the_ECMAScript_Specification">ECMAScript</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Introduction#Getting_started_with_JavaScript">Tools</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Introduction#Hello_world">Hello World</a></p> + </li> + <li><span><a href="/pt-PT/docs/Web/JavaScript/Guia/Gramática_e_tipos">Gramática e tipos</a></span> + <p><a href="/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#Basics">Basic syntax & comments</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#Declarations">Declarations</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#Variable_scope">Variable scope</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#Variable_hoisting">Variable hoisting</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#Data_structures_and_types">Data structures and types</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#Literals">Literals</a></p> + </li> + <li><span><a href="/en-US/docs/Web/JavaScript/Guide/Control_flow_and_error_handling">Controlo de fluxo e manipulação de erros</a></span> + <p><code><a href="/en-US/docs/Web/JavaScript/Guide/Control_flow_and_error_handling#if...else_statement">if...else</a></code><br> + <code><a href="/en-US/docs/Web/JavaScript/Guide/Control_flow_and_error_handling#switch_statement">switch</a></code><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Control_flow_and_error_handling#Exception_handling_statements"><code>try</code>/<code>catch</code>/<code>throw</code></a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Control_flow_and_error_handling#Utilizing_Error_objects">Error objects</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Control_flow_and_error_handling#Promises">Promises</a></p> + </li> + <li><span><a href="/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration">Loops e iteração</a></span> + <p><code><a href="/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration#for_statement">for</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration#while_statement">while</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration#do...while_statement">do...while</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration#break_statement">break</a>/<a href="/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration#continue_statement">continue</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration#for...in_statement">for..in</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration#for...of_statement">for..of</a></code></p> + </li> +</ul> + +<ul class="card-grid"> + <li><span><a href="/en-US/docs/Web/JavaScript/Guide/Functions">Funções</a></span> + + <p><a href="/en-US/docs/Web/JavaScript/Guide/Functions#Defining_functions">Defining functions</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Functions#Calling_functions">Calling functions</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Functions#Function_scope">Function scope</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Functions#Closures">Closures</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Functions#Using_the_arguments_object">Arguments</a> & <a href="/en-US/docs/Web/JavaScript/Guide/Functions#Function_parameters">parameters</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Functions#Arrow_functions">Arrow functions</a></p> + </li> + <li><span><a href="/pt-PT/docs/Web/JavaScript/Guia/Guia_expressões_e_operadores">Expressões e operadores</a></span> + <p><a href="/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#Assignment_operators">Assignment</a> & <a href="/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#Comparison_operators">Comparisons</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#Arithmetic_operators">Arithmetic operators</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#Bitwise_operators">Bitwise</a> & <a href="/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#Logical_operators">logical operators</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#Conditional_(ternary)_operator">Conditional (ternary) operator</a></p> + </li> + <li><span><a href="/en-US/docs/Web/JavaScript/Guide/Numbers_and_dates">Números e datas</a></span><a href="/en-US/docs/Web/JavaScript/Guide/Numbers_and_dates#Numbers"> Number literals</a> + <p><a href="/en-US/docs/Web/JavaScript/Guide/Numbers_and_dates#Number_object"><code>Number</code> object</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Numbers_and_dates#Math_object"><code>Math</code> object</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Numbers_and_dates#Date_object"><code>Date</code> object</a></p> + </li> + <li><span><a href="/en-US/docs/Web/JavaScript/Guide/Text_formatting">Formatação de texto</a></span> + <p><a href="/en-US/docs/Web/JavaScript/Guide/Text_formatting#String_literals">String literals</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Text_formatting#String_objects"><code>String</code> object</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Text_formatting#Multi-line_template_literals">Template literals</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Text_formatting#Internationalization">Internationalization</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Regular_Expressions">Regular Expressions</a></p> + </li> +</ul> + +<ul class="card-grid"> + <li><span><a href="/en-US/docs/Web/JavaScript/Guide/Indexed_collections">Coleções indexadas</a></span> + + <p><a href="/en-US/docs/Web/JavaScript/Guide/Indexed_collections#Array_object">Arrays</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Indexed_collections#Typed_Arrays">Typed arrays</a></p> + </li> + <li><span><a href="/en-US/docs/Web/JavaScript/Guide/Keyed_collections">Coleções Keyed</a></span> + <p><code><a href="/en-US/docs/Web/JavaScript/Guide/Keyed_collections#Map_object">Map</a></code><br> + <code><a href="/en-US/docs/Web/JavaScript/Guide/Keyed_collections#WeakMap_object">WeakMap</a></code><br> + <code><a href="/en-US/docs/Web/JavaScript/Guide/Keyed_collections#Set_object">Set</a></code><br> + <code><a href="/en-US/docs/Web/JavaScript/Guide/Keyed_collections#WeakSet_object">WeakSet</a></code></p> + </li> + <li><span><a href="/en-US/docs/Web/JavaScript/Guide/Working_with_Objects">Trabalhar com objetos</a></span> + <p><a href="/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#Objects_and_properties">Objets e propriedades</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#Creating_new_objects">Criação de objetos</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#Defining_methods">Definição de métodos</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#Defining_getters_and_setters">Getter and setter</a></p> + </li> + <li><span><a href="/en-US/docs/Web/JavaScript/Guide/Details_of_the_Object_Model">Detalhes do modelo de objeto</a></span> + <p><a href="/en-US/docs/Web/JavaScript/Guide/Details_of_the_Object_Model#Class-based_vs._prototype-based_languages">Prototype-based OOP</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Details_of_the_Object_Model#Creating_the_hierarchy">Creating object hierarchies</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Details_of_the_Object_Model#Property_inheritance_revisited">Inheritance</a></p> + </li> +</ul> + +<ul class="card-grid"> + <li><span><a href="/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators">Iterators e geradores</a></span> + + <p><a href="/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators#Iterators">Iterators</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators#Iterables">Iterables</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators#Generators">Generators</a></p> + </li> + <li><span><a href="/en-US/docs/Web/JavaScript/Guide/Meta_programming">Metadados de programação</a></span> + <p><code><a href="/en-US/docs/Web/JavaScript/Guide/Meta_programming#Proxies">Proxy</a></code><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Meta_programming#Handlers_and_traps">Handlers and traps</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Meta_programming#Revocable_Proxy">Revocable Proxy</a><br> + <code><a href="/en-US/docs/Web/JavaScript/Guide/Meta_programming#Reflection">Reflect</a></code></p> + </li> +</ul> + +<p>{{Next("Web/JavaScript/Guide/Introduction")}}</p> diff --git a/files/pt-pt/web/javascript/guia/introdução/index.html b/files/pt-pt/web/javascript/guia/introdução/index.html new file mode 100644 index 0000000000..f77bb74379 --- /dev/null +++ b/files/pt-pt/web/javascript/guia/introdução/index.html @@ -0,0 +1,137 @@ +--- +title: Introdução +slug: Web/JavaScript/Guia/Introdução +tags: + - Guía + - JavaScript +translation_of: Web/JavaScript/Guide/Introduction +--- +<div>{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide", "Web/JavaScript/Guide/Grammar_and_types")}}</div> + +<p class="summary">Este capítulo apresenta a linguagem JavaScript e discuste alguns dos seus conceitos fundamentais.</p> + +<h2 id="O_que_você_já_deveria_saber">O que você já deveria saber</h2> + +<p>Este guia assume que você possuí os seguintes conhecimentos:</p> + +<ul> + <li>Um conhecimento geral sobre Internet e o World Wide Web ({{Glossary("WWW")}}).</li> + <li>Bom conhecimento sobre como desenvolver em HyperText Markup Language ({{Glossary("HTML")}}).</li> + <li>Alguma experiência com programação. Caso seja iniciante nesse mundo, experimente seguir algum dos links com tutoriais que estão presentes na página principal sobre <a href="/pt-PT/docs/Web/JavaScript/Guia">JavaScript</a>.</li> +</ul> + +<h2 id="Onde_encontrar_informação_sobre_JavaScript">Onde encontrar informação sobre JavaScript?</h2> + +<p>A documentação de JavaScript no MDN incluí o seguinte:</p> + +<ul> + <li><a href="/pt-PT/docs/Learn">Aprender a Web</a> fornece informação para iniciantes e introduz os conceitos básicos sobre programação e Internet.</li> + <li><a href="/pt-PT/docs/Web/JavaScript/Guia">Guia de JavaScript</a> (este guia) fornece uma visão geral sobre a linguagem JavaScript e os seus objetos.</li> + <li><a href="/pt-PT/docs/Web/JavaScript/Reference">Referência de JavaScript</a> fornece conteúdos de referência detalhada para JavaScript.</li> +</ul> + +<p>Se for iniciante em JavaScript, comece lendo alguns dos artigos na <a href="/pt-PT/docs/Learn">área de aprendizagem</a> e o <a href="/pt-PT/docs/Web/JavaScript/Guia">Guia de JavaScript</a>. Assim que compreender os fundamentos da linguagem, pode consultar a <a href="/pt-PT/docs/Web/JavaScript/Reference">Referência de JavaScript</a> para obter mais detalhes sobre objetos individuais e declarações.</p> + +<h2 id="O_que_é_JavaScript">O que é JavaScript?</h2> + +<p>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.</p> + +<p>O JavaScript contém uma biblioteca padrão de objetos, tais como <code>Array</code>, <code>Date</code>, <code>Math</code>, 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:</p> + +<ul> + <li>JavaScript a correr no cliente extende a linguagem básica pois fornece objetos para controlar o browser e o seu Document Object Model (DOM). Por exemplo, extenções de cliente permitem a uma aplicação adicionar elementos num formulário HTML e responder a eventos do utilizador tais como cliques, input adicionado, e navegação na página.</li> + <li>JavaScript a correr no <span style="background-color: #f3a8a3;">servidor </span>extende a linguagem básica ao fornecer objetos relevantes para que isso aconteça. Por exemplo, extenções do lado do servidor permitem que uma aplicação comunique com uma base de dados, garante continuidade de informação entre invocações da aplicação, ou executa manipulações de ficheiros no servidor.</li> +</ul> + +<h2 id="JavaScript_and_Java" name="JavaScript_and_Java">JavaScript e Java</h2> + +<p>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.</p> + +<p>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.</p> + +<p>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.</p> + +<p>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.</p> + +<p>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.</p> + +<table class="standard-table"> + <caption>JavaScript comparado com Java</caption> + <thead> + <tr> + <th scope="col">JavaScript</th> + <th scope="col">Java</th> + </tr> + </thead> + <tbody> + <tr> + <td>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.</td> + <td>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.</td> + </tr> + <tr> + <td>Variable data types are not declared (dynamic typing).</td> + <td>Variable data types must be declared (static typing).</td> + </tr> + <tr> + <td>Cannot automatically write to hard disk.</td> + <td>Can automatically write to hard disk.</td> + </tr> + </tbody> +</table> + +<p>For more information on the differences between JavaScript and Java, see the chapter <a href="/pt-PT/docs/Web/JavaScript/Guia/Detalhes_do_modelo_de_objeto">Details of the object model</a>.</p> + +<h2 id="JavaScript_and_the_ECMAScript_Specification" name="JavaScript_and_the_ECMAScript_Specification">JavaScript e a especificação ECMAScript</h2> + +<p>JavaScript is standardized at <a class="external" href="http://www.ecma-international.org/">Ecma International</a> — 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 <a href="/en-US/docs/Web/JavaScript/New_in_JavaScript">New in JavaScript</a> to learn more about different versions of JavaScript and ECMAScript specification editions.</p> + +<p>The ECMA-262 standard is also approved by the <a class="external" href="http://www.iso.ch/">ISO</a> (International Organization for Standardization) as ISO-16262. You can also find the specification on <a class="external" href="http://www.ecma-international.org/publications/standards/Ecma-262.htm">the Ecma International website</a>. The ECMAScript specification does not describe the Document Object Model (DOM), which is standardized by the <a class="external" href="http://www.w3.org/">World Wide Web Consortium (W3C)</a> and/or <a href="https://whatwg.org">WHATWG (Web Hypertext Application Technology Working Group)</a>. 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 <a href="/en-US/docs/Web/JavaScript/JavaScript_technologies_overview">JavaScript technologies overview</a>.</p> + +<h3 id="JavaScript_Documentation_versus_the_ECMAScript_Specification" name="JavaScript_Documentation_versus_the_ECMAScript_Specification">Documentação JavaScript versus especificação ECMAScript</h3> + +<p>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).</p> + +<p>The ECMAScript document is not intended to help script programmers; use the JavaScript documentation for information on writing scripts.</p> + +<p>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.</p> + +<p>The JavaScript documentation describes aspects of the language that are appropriate for a JavaScript programmer.</p> + +<h2 id="Começar_com_JavaScript">Começar com JavaScript</h2> + +<p>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.</p> + +<p>There are two tools built into Firefox that are useful for experimenting with JavaScript: the Web Console and Scratchpad.</p> + +<h3 id="A_Consola_da_Web">A Consola da Web</h3> + +<p>A <a href="/pt-PT/docs/Tools/Consola_da_Web">Consola da Web</a> shows you information about the currently loaded Web page, and also includes a <a href="/en-US/docs/Tools/Web_Console#The_command_line_interpreter">command line</a> that you can use to execute JavaScript expressions in the current page.</p> + +<p>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:</p> + +<p><img alt="" src="https://mdn.mozillademos.org/files/7363/web-console-commandline.png" style="display: block; margin-left: auto; margin-right: auto;"></p> + +<h3 id="Scratchpad">Scratchpad</h3> + +<p>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 <a href="/en-US/docs/Tools/Scratchpad">Scratchpad</a> is a better tool.</p> + +<p>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.</p> + +<p><img alt="" src="https://mdn.mozillademos.org/files/7365/scratchpad.png" style="display: block; margin-left: auto; margin-right: auto;"></p> + +<h3 id="Olá_mundo">Olá mundo</h3> + +<p>To get started with writing JavaScript, open the Scratchpad and write your first "Hello world" JavaScript code:</p> + +<pre class="brush: js">function greetMe(yourName) { + alert("Hello " + yourName); +} + +greetMe("World"); +</pre> + +<p>Select the code in the pad and hit Ctrl+R to watch it unfold in your browser!</p> + +<p>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.</p> + +<p>{{PreviousNext("Web/JavaScript/Guide", "Web/JavaScript/Guide/Grammar_and_types")}}</p> diff --git a/files/pt-pt/web/javascript/guia/introdução_ao_javascript/index.html b/files/pt-pt/web/javascript/guia/introdução_ao_javascript/index.html new file mode 100644 index 0000000000..549ecbe331 --- /dev/null +++ b/files/pt-pt/web/javascript/guia/introdução_ao_javascript/index.html @@ -0,0 +1,47 @@ +--- +title: Introdução ao JavaScript +slug: Web/JavaScript/Guia/Introdução_ao_JavaScript +--- +<p>Este capítulo introduz o JavaScript e discute alguns de seus conceitos fundamentais.</p> +<h3 id="What_is_JavaScript.3F" name="What_is_JavaScript.3F">O que é o JavaScript?</h3> +<p>O JavaScript é uma linguagem de script multiplataforma, orientada a objetos. O JavaScript é uma linguagem pequena e leve; não é útil como uma linguagem de uso isolado, mas é projetada para fácil integração em outros produtos e aplicações, tais como navegadores web. Dentro de um ambiente de hospedagem, o JavaScript pode ser conectado aos objetos de seu ambiente para proporcionar um controle programático sobre elas.</p> +<p>O núcleo do JavaScript contém um núcleo de objetos, como <code>Array</code>, <code>Date</code>, e <code>Math</code>, e um núcleo de elementos de linguagem como operadores, estruturas de controle, e declarações. O núcleo do JavaScript pode ser extendido para uma variedade de propósitos complementando-o com objetos adicionais; por exemplo:</p> +<ul> <li><em>O lado do cliente no JavaScript</em> extende o núcleo da linguagem fornecendo objetos para controlar um navegador (Navigator ou outro navegador web) e seu Document Object Model (DOM). Por exemplo, extensões para o lado do cliente permitem a uma aplicação colocar elementos em um formulário HTML e responder a eventos de usuários como cliques de mouse, entrada de dados e navegação na página.</li> <li><em>O lado do servidor no JavaScript</em> extende o núcleo da linguagem fornecendo objetos relevantes à execução de JavaScript no servidor. Por exemplo, extensões do lado do servidor permitem a uma aplicação comunicar-se com um banco de dados relacional, proporcionar continuidade de informação de uma invocação da aplicação para outra, ou executar manipulações de arquivos em um servidor.</li> +</ul> +<p>Através da funcionalidade JavaScript's LiveConnect, pode-se permitir que códigos em Java e em JavaScript comuniquem-se. É possível instanciar objetos Java e acessar seus métodos e campos públicos a partir do JavaScript. A partir do Java, por sua vez, pode-se acessar objetos, propriedades e métodos do JavaScript.</p> +<p>O Netscape inventou o JavaScript e o JavaScript foi inicialmente usado em navegadores Netscape.</p> +<h3 id="JavaScript_and_Java" name="JavaScript_and_Java">JavaScript e Java</h3> +<p>O JavaScript e o Java são similares em algumas coisas, mas fundamentalmente diferentes em outras. A linguagem JavaScript assemelha-se ao Java, mas não possui a checagem de tipos forte e digitação estática do Java. O JavaScript suport a maioria das sintaxes de expressões em Java e um construtor básico de controles de fluxo.</p> +<p>Em contraste com o sistema em tempo de compilação do Java, de classes construídas por declarações, o JavaScript suporta um sistema de tempo de execução baseado em um pequeno número de tipos de dados representando números, booleanos, e valores de strings. O JavaScript possui um modelo de objetos baseado em protótipos, ao invés do mais comum, modelo de objetos baseado em classes. O modelo baseado em protótipos provê a herança dinâmica; isto é, o que é herdado pode variar para objetos individuais. O JavaScript também suporta funções sem requisições especiais de declaração. Funções podem ser propriedades de objetos, executando métodos fracamente tipados.</p> +<p>O JavaScript é uma linguagem com forma bastante livre comparada ao Java. Você não precisa declarar todas as variáveis, classes e métodos. Você não precisa se preocupar se os métodos são públicos, privados ou protegidos, e você não precisa implementar interfaces. Tipos de variáveis, parâmetros e retornos de funções não são explicitados.</p> +<p>O Java é uma linguagem de programação baseada em classes e projetava para rápida execução e tipagem segura. Tipagem segura significa, por exemplo, que você não pode converter um inteiro do Java para uma referência de um objeto ou acessar a memória privada, corrompendo bytecodes do Java. O modelo baseado em classes do Java significa que o programa consiste exclusivamente de classes e seus métodos. A herança das classes no Java e a tipagem forte, geralmente requerem objetos com hierarquias firmemente acopladas. Estes requisitos fazem do Java uma linguagem de programação mais complexa que a autoria do JavaScript.</p> +<p>Em contraste, o JavaScript descende em espírito de uma linha menor, linguagens tipadas dinamicamente, tais como HyperTalk e dBASE. Estas linguagens de stript oferecem ferramentas de programação para um público muito maior, devido a simplicidade de sua sintaxe, funcionalidades especializadas integradas e requisitos mínimos para criação de objetos.</p> +<table class="standard-table"> <caption>Tabela 1.1 JavaScript em comparação ao Java</caption> <thead> <tr> <th scope="col">JavaScript</th> <th scope="col">Java</th> </tr> </thead> <tbody> <tr> <td>Orientação a objetos. Sem distinção entre tipos de objetos. A herança ocorre através do mecanismo de protótipos e os métodos e propriedades podem ser adicionados a qualquer objeto dinamicamente.</td> <td>Baseada em classes. Objetos são divididos em classes e instâncias com toda a herança através da hierarquia da classe. Classes e instâncias não podem ter métodos e propriedades adicionados dinamicamente.</td> </tr> <tr> <td>Tipos de dados variáveis não são declarados (tipagem dinâmica).</td> <td>Tipos de dados variáveis precisam ser declarados (tipagem estática).</td> </tr> <tr> <td>Não pode escrever automaticamente no disco rígido.</td> <td>Não pode escrever automaticamente no disco rígido.</td> </tr> </tbody> +</table> +<p>Para mais informações sobre as diferenças entre o JavaScript e o Java, veja o capítulo <a href="/en/JavaScript/Guide/Details_of_the_Object_Model" title="en/JavaScript/Guide/Details of the Object Model">Details of the Object Model</a>.</p><h3 id="JavaScript_and_the_ECMAScript_Specification" name="JavaScript_and_the_ECMAScript_Specification">JavaScript e a especificação ECMAScript</h3> +<p>O Netscape inventou o JavaScript e o JavaScript foi primeiramente usado nos navegadores Netscape. Entretanto, a Netscape está trabalhando com a <a class="external" href="http://www.ecma-international.org/">Ecma International</a> — a associação européia para padronizão de informação e sistemas de comunicação (formalmente conhecida como ECMA - European Computer Manufacturers Association, em português: Associação de Fabricantes de Computadores Europeus) — para entregar uma linguagem de programação internacional padronizada, baseada no JavaScript. Esta versão padronizada do JavaScript, chamada de ECMAScript, comporta-se da mesma maneira em todas as aplicações que suportem o padrão. Empresas podem usar a linguagem padrão aberta para desenvolver sua implementação do JavaScript. O ECMAScript padrão é documentado na especificação ECMA-262.</p> +<p>O padrão ECMA-262 é também aprovado pela <a class="external" href="http://www.iso.ch/">ISO</a> (International Organization for Standardization, em português: Organização Internacional para Padronização) como ISO-16262. Você pode encontrar uma <a class="external" href="http://www.mozilla.org/js/language/E262-3.pdf">versão PDF do ECMA-262</a> (en) no site da Mozilla. Você pode também encontrar a especificação em <a class="external" href="http://www.ecma-international.org/publications/standards/Ecma-262.htm">the Ecma International website</a> (en). A especificação do ECMAScript não descreve o Document Object Model (DOM), o qual é padronizado pelo <a class="external" href="http://www.w3.org/">World Wide Web Consortium (W3C)</a>. O DOM define a maneira com a qual os objetos do documento HTML são expostos ao seu script.</p> +<h4 id="Relationship_between_JavaScript_Versions_and_ECMAScript_Editions" name="Relationship_between_JavaScript_Versions_and_ECMAScript_Editions">Relação entre as versões do JavaScript e as edições do ECMAScript</h4> +<p>O Netscape trabalhou próximo a Ecma International para produzir a Especificação ECMAScript (ECMA-262). A tabela seguinte descreve a relação entre as versões do JavaScript e as edições do ECMAScript.</p> +<table class="standard-table"> <caption>Tabela 1.2 Versões do JavaScript e edições do ECMAScript</caption> <thead> <tr> <th scope="row">Versão do JavaScript</th> <th scope="col">Relação com a edição do ECMAScript</th> </tr> </thead> <tbody> <tr> <td>JavaScript 1.1</td> <td>O ECMA-262, Edição 1 é baseado no JavaScript 1.1.</td> </tr> <tr> <td>JavaScript 1.2</td> <td>O ECMA-262 não estava completo quando o JavaScript 1.2 foi lançado. O JavaScript 1.2 não é totalmente compatível com o ECMA-262, Edição 1, pelas seguintes razões: <ul> <li>O Netscape desenvolveu características adicionais no JavaScript 1.2 que não foram consideradas no ECMA-262.</li> <li>O ECMA-262 adiciona duas novas características: internacionalização usando Unicode e comportamento uniforme em todas as plataformas. Muitas características do JavaScript 1.2, tais com o objeto <code>Date</code>, eram dependentes de plataforma e usavam um comportamento específico da plataforma.</li> </ul> </td> </tr> <tr> <td> <p>JavaScript 1.3</p> </td> <td> <p>O JavaScript 1.3 é totalmente compatível com o ECMA-262, Edição 1.</p> <p>O JavaScript 1.3 corrigiu as inconsistências que o JavaScript 1.2 tinha com o ECMA-262, mantendo todas as características adicionais do JavaScript 1.2 com a exceção de == e !=, os quais foram mudados conforme o ECMA-262.</p> </td> </tr> <tr> <td> <p>JavaScript 1.4</p> </td> <td> <p>O JavaScript 1.4 é totalmente comatível com o ECMA-262, Edição 1.</p> <p>A terceira versão da especificação ECMAScript não estava finalizada quando o JavaScript 1.4 foi lançado.</p> </td> </tr> <tr> <td>JavaScript 1.5</td> <td>O JavaScript 1.5 é totalmente compatível com o ECMA-262, Edição 3.</td> </tr> </tbody> +</table> +<div class="note"><strong>Nota</strong>: O ECMA-262, Edição 2 consistiu de mudanças editoriais pequenas e correções de bugs da especificação da Edição 1. O grupo de trabalho TC39 da Ecma International está atualmente trabalhando no ECMAScript Edição 4, o qual corresponderá a um lançamento futuro do JavaScript, o JavaScript 2.0.</div> +<p>A <a href="/en/JavaScript/Reference" title="en/JavaScript/Reference">Referência de JavaScript</a> (en) indica quais características da linguagem estão em conformidade com o ECMAScript.</p> +<p>O JavaScript sempre permite incluir características que não fazem parte da Especificação do ECMAScript; O JavaScript é compatível com o ECMASCript; mesmo provendo características adicionais.</p><h4 id="JavaScript_Documentation_versus_the_ECMAScript_Specification" name="JavaScript_Documentation_versus_the_ECMAScript_Specification">Documentação do JavaScript versus a especificação do ECMAScript</h4> +<p>A especificação do ECMAScript é um conjunto de requisitos para a implementação do ECMAScript; ela é útil caso deseje-se determinar, se uma característica do JavaScript é suportada em outras implementações do ECMAScript. Caso planeje-se escrever código JavaScript usando somente características suportadas pelo ECMAScript, então é interessante checar a especificação ECMAScript.</p> +<p>O documento ECMAScript não pretende ajudar programadores de scripts; para informações sobre escrita de scripts, deve-se usar a documentação do JavaScript.</p><h4 id="JavaScript_and_ECMAScript_Terminology" name="JavaScript_and_ECMAScript_Terminology">Terminologia do JavaScript e do ECMAScript</h4> +<p>A especificação do ECMAScript utiliza a terminologia e sintaxe que pode ser desconhecida para um programador JavaScript. Embora a descrição da linguagem possa diferir, a linguagem em si, é a mesma. O JavaScript suporta todas as funcionalidades descritas na especificação ECMAScript.</p> +<p>A documentação do JavaScript descreve aspectos da linguagem que são apropriados para um programador JavaScript. Por exemplo:</p> +<ul> <li>O Objeto Global não é discutido na documentação do JavaScript porque ele não é usado diretamente. Os métodos e propriedades do Objeto Global, os quais são usados, são discutidos na documentação do JavaScript, mas são chamados de funções e propriedades de nível superior.</li> <li>O construtor sem parâmetros (zero argumentos) com os objetos <code>Number</code> e <code>String</code> não é discutido na documentação do JavaScript, pois o gerado é pouco usado. Um construtor de <code>Number</code> sem nenhum argumento, retorna +0, e um construtor de <code>String</code> sem argumentos, retorna "" (uma string vazia).</li> +</ul> +<pre class="script" style="font-size: 16px;">autoPreviousNext("JSGChapters"); +wiki.languages({ + "en": "en/JavaScript/Guide/JavaScript_Overview", + "es": "es/Gu\u00eda_JavaScript_1.5/Concepto_de_JavaScript", + "fr": "fr/Guide_JavaScript_1.5/Aper\u00e7u_de_JavaScript", + "ja": "ja/Core_JavaScript_1.5_Guide/JavaScript_Overview", + "ko": "ko/Core_JavaScript_1.5_Guide/JavaScript_Overview", + "pl": "pl/Przewodnik_po_j\u0119zyku_JavaScript_1.5/Przegl\u0105d_JavaScriptu", + "zh-cn": "cn/Core_JavaScript_1.5_Guide/JavaScript\u603b\u89c8", + "zh-tw": "zh_tw/Core_JavaScript_1.5_教學/JavaScript_概要" +});</pre> diff --git a/files/pt-pt/web/javascript/guia/sobre/index.html b/files/pt-pt/web/javascript/guia/sobre/index.html new file mode 100644 index 0000000000..6957645a40 --- /dev/null +++ b/files/pt-pt/web/javascript/guia/sobre/index.html @@ -0,0 +1,166 @@ +--- +title: Sobre este guia +slug: Web/JavaScript/Guia/Sobre +--- +<p>JavaScript é uma linguagem de scripts multiplataforma, baseada em objetos. Este guia explica tudo que é necessário saber sobre como utilizar o JavaScript.</p> + +<h2 id="Novas_caraterísticas_em_versões_do_JavaScript">Novas caraterísticas em versões do JavaScript</h2> + +<pre class="script" style="font-size: 16px;">/* Nota: Para adicionar um link na descrição de uma nova versão do JavaScript, +adicione o número da variável versionList abaixo. A página ligada deve +residir em /en/JavaScript/New_in_JavaScript/N, onde N é o número da versão. */ + +var versionList = ["1.5", "1.6", "1.7", "1.8", "1.8.1", "1.8.5"]; +var s = ""; +<ul> + foreach (var i in versionList){ + let s = "/en/JavaScript/New_in_JavaScript/" .. i; + <li>web.link(s, wiki.getPage(s).title)</li>; + } +</ul>;</pre> + +<h2 id="O_que_já_é_necessário_saber">O que já é necessário saber</h2> + +<p>Este guia assume que já possui os seguintes conhecimentos como base:</p> + +<ul> + <li>Um entendimento geral da Internet e da World Wide Web (WWW).</li> + <li>Bom conhecimento de trabalho com HyperText Markup Language (<a href="/en/HTML" title="en/HTML">HTML</a>).</li> +</ul> + +<p>Alguma experiência de programação com uma linguagem como C ou Visual Basic é útil, mas não necessária.</p> + +<h2 id="Versões_do_JavaScript">Versões do JavaScript</h2> + +<table class="standard-table"> + <caption>Tabela 1 Versões do JavaScript e do Navigator</caption> + <thead> + <tr> + <th scope="col">versão JavaScript</th> + <th scope="col">versão Navigator</th> + </tr> + </thead> + <tbody> + <tr> + <td>JavaScript 1.0</td> + <td>Navigator 2.0</td> + </tr> + <tr> + <td>JavaScript 1.1</td> + <td>Navigator 3.0</td> + </tr> + <tr> + <td>JavaScript 1.2</td> + <td>Navigator 4.0-4.05</td> + </tr> + <tr> + <td>JavaScript 1.3</td> + <td>Navigator 4.06-4.7x</td> + </tr> + <tr> + <td>JavaScript 1.4</td> + <td> </td> + </tr> + <tr> + <td>JavaScript 1.5</td> + <td>Navigator 6.0<br> + Mozilla (navegador open source)</td> + </tr> + <tr> + <td>JavaScript 1.6</td> + <td><a href="/en/Firefox_1.5_for_developers" title="en/Firefox_1.5_for_developers">Firefox 1.5</a>, outros produtos baseados no Mozilla 1.8</td> + </tr> + <tr> + <td>JavaScript 1.7</td> + <td><a href="/en/Firefox_2_for_developers" title="en/Firefox_2_for_developers">Firefox 2</a>, outros produtos baseados no Mozilla 1.8.1</td> + </tr> + <tr> + <td>JavaScript 1.8</td> + <td><a href="/en/Firefox_3_for_developers" title="en/Firefox_3_for_developers">Firefox 3</a>, outros produtos baseados no Gecko 1.9</td> + </tr> + </tbody> +</table> + +<p>Cada versão do Netscape Enterprise Server também suporta diferentes versões do JavaScript. Para ajudar na escrita de scripts compatíveis com múltiplas versões do Enterprise Server, este manual usa uma abreviação para indicar a versão do servidor na qual cada característica foi implementada.</p> + +<table class="standard-table"> + <caption>Tabela 2 Abreviações das versões do Netscape Enterprise Server</caption> + <thead> + <tr> + <th scope="col">Abreviação</th> + <th scope="col">versão Enterprise Server</th> + </tr> + </thead> + <tbody> + <tr> + <td>NES 2.0</td> + <td>Netscape Enterprise Server 2.0</td> + </tr> + <tr> + <td>NES 3.0</td> + <td>Netscape Enterprise Server 3.0</td> + </tr> + </tbody> +</table> + +<h2 id="Onde_encontrar_informações_sobre_JavaScript">Onde encontrar informações sobre JavaScript</h2> + +<p>A documentação do JavaScript inclui os seguintes livros:</p> + +<ul> + <li><a href="/en/JavaScript/Guide" title="en/Core_JavaScript_1.5_Guide">Guia de JavaScript</a> (este guia) fornece informações sobre a linguagem JavaScript e seus objetos.</li> + <li><a href="/en/JavaScript/Reference" title="en/JavaScript/Reference">Referência JavaScript</a> fornece material de referência para a linguagem JavaScript.</li> +</ul> + +<p>Se você é novo no JavaScript, comece com o <a href="/en/JavaScript/Guide" title="en/Core_JavaScript_1.5_Guide">Guia de JavaScript</a>. Uma vez que você tenha uma boa compreensão dos fundamentos, você pode usar a <a href="/en/JavaScript/Reference" title="en/JavaScript/Reference">Referência JavaScript</a> para obter mais detalhes sobre objetos e declarações.</p> + +<h2 id="Dicas_para_aprender_JavaScript">Dicas para aprender JavaScript</h2> + +<p>Começar com o JavaScript é fácil: é necessário apenas um navegador web moderno. Este guia inclui algumas características do JavaScript que estão atualmente disponíveis nas últimas versões do Firefox (e outros navegadores baseados no Gecko), é recomendado, portanto, o uso da versão mais recente do Firefox.</p> + +<h3 id="Um_interpretador_interativo">Um interpretador interativo</h3> + +<p>Uma linha de comando interativa com JavaScript é inestimável para o aprendizado da linguagem, pois permite experimentar código de forma interativa sem ter que salvar um arquivo e recarregar a página. O Console de erros do Firefox, acessível através do menu de Ferramentas, fornece uma maneira simples de testar JavaScript interativamente: Basta entrar uma linha de código e clicar no botão "Executar".</p> + +<p><img alt="Image:ErrorConsole.png" class="internal" src="/@api/deki/files/192/=ErrorConsole.png"></p> + +<h3 id="Firebug">Firebug</h3> + +<p>Uma linha de comando interativa mais avançada está disponível com o uso do<a class="external" href="http://www.getfirebug.com/"> Firebug</a>, uma extensão de terceiros para o Firefox. O Firebug também fornece um inspetor DOM avançado, um depurador de JavaScript, uma ferramenta de análise e vários outros utilitários.</p> + +<p><img alt="Image:Firebug.png" class="internal" src="/@api/deki/files/204/=Firebug.png"></p> + +<p>Um dos mais úteis benefícios proporcionados pelo Firebug é <code>console.log()</code>, uma função que imprime seus argumentos no console do Firebug. Diferentemente de outras linguagens de programação, o JavaScript não possui um conceito de impressão para a saída padrão. O <code>console.log()</code> fornece uma alternativa útil, tornando mais fácil ver o que seu programa está fazendo.</p> + +<p>Muitos dos exemplos neste guia usam <code>alert()</code> para exibir mensagens conforme são executados. Tendo o Firebug instalado, pode ser usando <code>console.log()</code> ao invés de <code>alert()</code> ao rodar estes exemplos.</p> + +<h2 id="Convenções_de_documento">Convenções de documento</h2> + +<p>Aplicações JavaScript rodam em muitos sistemas operacionais; a informação neste livro aplica-se a todas as versões. Os caminhos de arquivos e diretórios são dados no formato Windows (com contrabarras separando os nomes dos diretórios). Para versões Unix, os caminhos são os mesmo, exceto por serem usadas barras ao invés de contrabarras para separar os diretórios.</p> + +<p>Este guia usa localizador padrão de recursos (<em>uniform resource locators</em> (URL)) da seguinte forma:</p> + +<p><code>http://<em>server</em>.<em>domain</em>/<em>path</em>/<em>file</em>.html</code></p> + +<p>Nestas URL, <em>server</em> representa o nome do servidor no qual a aplicação é rodada, tal como <code>research1</code> ou <code>www</code>; <em>domain</em> representa seu domínio de internet, como <code>netscape.com</code> ou <code>uiuc.edu</code>; <em>path</em> representa a estrutura do diretório no servidor; e <em>file</em><code>.html</code> representa o nome de um arquivo individual. No geral, itens em itálico em são <em>placeholders</em> e itens em fonte monoespaçada normal são literais. Se o servidor possuir <em>Secure Sockets Layer</em> (SSL) habilitado, pode ser usado <code>https</code> ao invés de <code>http</code> na URL.</p> + +<p>Este guia utiliza as seguintes convenções de fontes:</p> + +<ul> + <li><code>A fonte mono espaçada</code> é utilziada para amostras de código e listagens de código, API e elementos da linguagem (como nomes de métodos e propriedades), nome de arquivos, caminhos, diretórios, tags HTML, e qualquer texto que possa ser digitado na tela. (<code><em>A fonte monoespaçada itálica</em></code> é usada para <em>placeholders </em>embutidos no código.)</li> + <li><em>O tipo itálico</em> é usado para títulos de livros, ênfase, variáveis e <em>placeholders</em>, e palavras usadas em sentido literal.</li> + <li><strong>O tipo negrito</strong> é usado para termos de glossário.</li> +</ul> + +<pre class="script" style="font-size: 16px;">autoPreviousNext("JSGChapters"); +wiki.languages({ + "en": "en/JavaScript/Guide/About", + "es": "es/Gu\u00eda_JavaScript_1.5/Acerca_de_esta_gu\u00eda", + "fr": "fr/Guide_JavaScript_1.5/\u00c0_propos", + "ja": "ja/Core_JavaScript_1.5_Guide/About", + "ko": "ko/Core_JavaScript_1.5_Guide/About", + "pl": "pl/Przewodnik_po_j\u0119zyku_JavaScript_1.5/O_tym_przewodniku", + "zh-cn": "cn/Core_JavaScript_1.5_Guide/\u5173\u4e8e", + "zh-tw": "zh_tw/Core_JavaScript_1.5_教學/關於" +}) +</pre> diff --git a/files/pt-pt/web/javascript/guia/valores,_variáveis_e_literais/index.html b/files/pt-pt/web/javascript/guia/valores,_variáveis_e_literais/index.html new file mode 100644 index 0000000000..c2cbc7f3db --- /dev/null +++ b/files/pt-pt/web/javascript/guia/valores,_variáveis_e_literais/index.html @@ -0,0 +1,547 @@ +--- +title: 'Valores, Variáveis e Literais' +slug: 'Web/JavaScript/Guia/Valores,_Variáveis_e_Literais' +--- +<p>Este capítulo discute valores reconhecidos pelo JavaScript e descreve a construção de blocos fundamentais de expressões em JavaScript: variáveis, constantes e literais.</p> + +<h2 id="Valores">Valores</h2> + +<p>O JavaScript reconhece os seguintes tipos de valores:</p> + +<ul> + <li><a href="/en/JavaScript/Reference/Global_Objects/Number" title="en/JavaScript/Reference/Global Objects/Number">Números</a> (en), como 42 ou 3,14159</li> + <li>Valores <a href="/en/JavaScript/Reference/Global_Objects/Boolean" title="en/JavaScript/Reference/Global Objects/Boolean">lógicos (Booleanos)</a> (en), <code>true</code> ou <code>false</code></li> + <li><a href="/en/JavaScript/Reference/Global_Objects/String" title="en/JavaScript/Reference/Global Objects/String">Strings</a> (en), tais como "Howdy!"</li> + <li><code>null</code>, um palavra chave especial denotando um valor nulo; <code>null</code> também é um valor primitivo. Como JavaScript é sensível a maiúsculas, <code>null</code> não é a mesma coisa que <code>Null</code>, <code>NULL</code>, ou qualquer outra variante</li> + <li><code><a href="/en/JavaScript/Reference/Global_Objects/undefined" title="en/JavaScript/Reference/Global Objects/undefined">undefined</a></code> (en), uma propriedade de alto nível a qual possui o valor indefinido; <code>undefined</code> também é um valor primitivo.</li> +</ul> + +<p>Este conjunto de tipos de valores relativamente pequeno, permite realizar funções úteis com suas aplicações. Não há distinção explícita entre números inteiros e reais. Nem existe um tipo de dados de datas explícito em JavaScript. Entretanto, é possível utilizar o objeto <code><a href="/en/JavaScript/Reference/Global_Objects/Date" title="en/JavaScript/Reference/Global Objects/Date">Date</a></code> (en) e seus métodos para lidar com datas.</p> + +<p><a href="/en/JavaScript/Reference/Global_Objects/Object" title="en/JavaScript/Reference/Global Objects/Object">Objetos</a> (en) e <a href="/en/JavaScript/Reference/Global_Objects/Function" title="en/JavaScript/Reference/Global Objects/Function">funções</a> (en) são os outros elementos fundamentias da linguagem. Pode-se pensar em objetos como nomes nos quais podem ser guardados valores, e funções como procedimentos que sua aplicação pode executar.</p> + +<h3 id="Conversão_de_tipos_de_dados">Conversão de tipos de dados</h3> + +<p>O JavaScript é uma linguagem de tipagem dinâmica. Isto significa que não é necessário especificar o tipo de dado de uma variável quando ela for declarada, e tipos de dados são automaticamento convertidos conforme necessário durante a execução do script. Então, por exemplo, pode-se definir uma variável como:</p> + +<pre>var resposta = 42; +</pre> + +<p>E depois, pode-se atribuir para a mesma variável um valor de string, por exemplo:</p> + +<pre class="deki-transform">resposta = "Obrigado pelos peixes..."; +</pre> + +<p>Como o JavaScript possui tipagem dinâmica, esta atribuição não gera uma mensagem de erro.</p> + +<p>Em expressões envolvendo valores numéricos e strings com o operador +, o JavaScript converte valores numérios para string. Por exemplo, considere as seguintes declarações:</p> + +<pre class="eval deki-transform">x = "A resposta é " + 42 // retorna "A resposta é 42" +y = 42 + " é a resposta" // retorna "42 é a resposta" +</pre> + +<p>Em declarações envolvendo outros operadores, o JavaScript não converte valores numérico para strings. Por exemplo:</p> + +<pre class="eval deki-transform">"37" - 7 // retorna 30 +"37" + 7 // retorna "377"</pre> + +<h2 id="Variáveis">Variáveis</h2> + +<p>Variáveis são usadas como nomes simbólicos para valores em sua aplicação. Os nomes das variáveis, chamadas <em>identificadores</em>, de acordo com certas regras.</p> + +<p>Um identificador JavaScript deve começar com uma letra, sublinhado (_), ou cifrão ($); caracteres subsequentes podem também ser dígitos (0-9). Como o JavaScript é sensível a maiúsculas, as letras incluem os caracteres de "A" até "Z" (maiúsculas) e os caracteres de "a" até "z" (minúsculas).</p> + +<p>A partir do JavaScript 1.5 é possível usar letras em ISO 8859-1 ou Unicode tais como å e ü nos identificadores. Também é possível usar as <a href="#Sequências de escape em Unicode">Sequências de escape em Unicode</a> \uXXXX como caracteres nos identificadores.</p> + +<p>Alguns exemplos de nomes possíveis são: <code>Number_hits</code>, <code>temp99</code> e <code>_name</code>.</p> + +<h3 id="Declaração_de_variáveis">Declaração de variáveis</h3> + +<p>Você pode declarar uma variável de duas maneiras:</p> + +<ul> + <li>Com a palavra chave <a href="/en/JavaScript/Reference/Statements/var" title="en/JavaScript/Reference/Statements/var">var</a>. Por exemplo, <code>var x = 42</code>. Esta sintaxe pode ser usada para declarar tanto variáveis <a href="#Variable_Scope">locais quanto globais</a> (en).</li> + <li>Simplesmente atribuindo um valor a ela. Por exemplo, <code>x = 42</code>. Isto sempre declara uma <a href="#Global_Variables">variável global</a> (en) e gera um aviso estrito do JavaScript. Esta variante não deve ser usada.</li> +</ul> + +<h3 id="Avaliação_de_variáveis">Avaliação de variáveis</h3> + +<p>Uma variável declarada usando-se a declaração <code>var</code> sem possuir um valor inicial especificado possui o valor <code><a href="/en/JavaScript/Reference/Global_Objects/undefined" title="en/JavaScript/Reference/Global Objects/undefined">undefined</a></code>.</p> + +<p>Uma tentativa de acesso a uma variável não declarada resultará no lançamento de uma exceção <code>ReferenceError</code>:</p> + +<pre class="eval deki-transform">var a; +print("O valor de a é " + a); // imprime "O valor de a é undefined" +print("O valor de b é " + b); // lança a exceção ReferenceError +</pre> + +<p>Você pode usar <code>undefined</code> para determinar quando uma variável possui um valor. No código a seguir, a variável <code>input</code> não possui um valor atribuido e a declaração <code><a href="/en/JavaScript/Reference/Statements/if...else" title="en/Core_JavaScript_1.5_Reference/Statements/if...else">if</a></code> é avaliada como <code>true</code>.</p> + +<pre class="eval deki-transform">var input; +if(input === undefined){ + doThis(); +} else { + doThat(); +} +</pre> + +<p><span class="comment">O valor</span> <code>undefined</code> comporta-se como <code>false</code> quando usado em um contexto booleano. Por exemplo, o código a seguir executa a função <code>myFunction</code> porque o elemento <code>myArray</code> não está definido:</p> + +<pre class="eval deki-transform">var myArray = new Array(); +if (!myArray[0]) myFunction(); +</pre> + +<p>Quando você avalia uma variável nula, o valor nulo comporta-se como um 0 no contexto numérico e como falso em contextos booleanos. Por exemplo</p> + +<pre class="eval deki-transform">var n = null; +print(n * 32); // imprime 0 +</pre> + +<h3 id="Escopo_de_variáveis">Escopo de variáveis</h3> + +<p>Quando uma variável é declarada de fora de qualquer função, ele é chamada de variável <em>global</em>, pois ela está disponível para qualquer outro código no documento atual. Quando você declara uma variável dentro de uma função, ela é chamada de variável <em>local</em>, pois ela está disponível somente dentro dessa função.</p> + +<p>O JavaScript não possui um escopo de <a href="/en/JavaScript/Guide/Statements#Block_Statement" title="en/JavaScript/Guide/Statements#Block Statement">declaração de blocos</a> (en); ao contrário, será local para o código interno ao bloco. Por exemplo, o código a seguir imprimirá <code>0</code> ao invés de lançar a exceção <span><span class="comment">ReferenceError se</span></span> <code>condition</code> é <code>false</code>:</p> + +<pre class="eval deki-transform">if (condition) { + var x = 5; +} +print(x ? x : 0); +</pre> + +<p>Outra coisa não usual sobre variáveis em JavaScript é que é possível referir-se a uma variável declarada depois, sem receber uma exceção. Este conceito é conhecido como <em>hoisting</em>; as variáveis no JavaScript são levadas para o topo da função ou da declaração. Entretanto, as variáveis não inicializadas retornarão um valor <code>undefined</code>.</p> + +<pre class="eval deki-transform">print(x === undefined); // prints "true" +var x = 3; + +//will return a value of undefined +var myvar = "my value"; + +(function() { + alert(myvar);//undefined + var myvar = "local value" +})(); +</pre> + +<h3 id="Variáveis_globais">Variáveis globais</h3> + +<p><span class="comment">necessário links para as páginas discutindo cadeias no âmbito do objeto global</span> Variáveis globais são, na verdade, propriedade de um <em>objeto global</em>. Em páginas web o objeto global é <code><a href="/en/DOM/window" title="en/DOM/window">window</a></code>, então você pode configurar e acessar variáveis globais usando a sintaxe<code> window.<em>variable</em></code>.</p> + +<p>Consequentemente, você pode acessar variáveis globais declaradas em uma janela ou quadro de alguma outra janela ou quadro, especificando o nome do mesmo. Por exemplo, se uma variável chamada <code>phoneNumber</code> é declarada em um documento <code>FRAMESET</code>, você pode referir-se a esta variável a partir de um frame herdeiro como <code>parent.phoneNumber</code>.</p> + +<h3 id="Veja_também">Veja também</h3> + +<p><a href="/en/Sharp_variables_in_JavaScript" title="en/Sharp_variables_in_JavaScript">Sharp variables in JavaScript</a> (en)</p> + +<h2 id="Constantes">Constantes</h2> + +<p>Você pode criar elementos "somente leitura", nomeados constantes com a palavra chave <code><a href="/en/JavaScript/Reference/Statements/const" title="en/Core_JavaScript_1.5_Reference/Statements/const">const</a></code>. A sintaxe de um identificador constante é a mesma para um identificador de variáveis: deve começar com uma letra ou sublinhado e pode conter caracteres alfabéticos, numéricos ou sublinhado.</p> + +<pre class="eval deki-transform">const prefix = '212'; +</pre> + +<p>Uma constante não pode ter seu valor mudado através de uma atribuição ou ser declarada novamente enquanto o script estiver rodando.</p> + +<p>As regras de escopo para constantes são as mesmas que as das variáveis, exceto que a palavra chave <code>const</code> é sempre necessária, mesmo para constantes globais. Se uma palavra chave é omitida, o identificador é assumido como uma variável.</p> + +<p>Você não pode declarar uma constante com o mesmo nome de uma função ou variável no mesmo escopo. Por exemplo:</p> + +<pre class="eval deki-transform">// ISTO CAUSARA UM ERRO +function f() {}; +const f = 5; + +// ISTO TAMBEM CAUSARA UM ERRO +function f() { + const g = 5; + var g; + + // declaracoes +} +</pre> + +<h2 id="Literais">Literais</h2> + +<p>Você usa literais para representar valores em JavaScript. Estes valores são fixos, não variáveis, que você fornece <em>literalmente</em> no seu script. Esta seção descreve os seguintes tipos de literais:</p> + +<ul> + <li><a href="#Ordenação de literais">Ordenação de literais</a></li> + <li><a href="#Booleanos literais">Booleanos literais</a></li> + <li><a href="#Pontos flutuantes literais">Pontos flutuantes literais</a></li> + <li><a href="#Inteiros">Inteiros</a></li> + <li><a href="#Objetos literais">Objetos literais</a></li> + <li><a href="#Strings literais">Strings literais</a></li> +</ul> + +<h3 id="Ordenação_de_literais"><a id="Ordenação de literais" name="Ordenação de literais">Ordenação de literais</a></h3> + +<p>Um literal ordenado é uma lista de zero ou mais expressões, cada qual representando um elemento ordenado, armazenado em colchetes ([]). Quando você cria uma ordenação usando um literal ordenado, ele é inicializado com os valores especificados como seus elementos e seu comprimento configurado para o número de argumentos especificados.</p> + +<p>O exemplo a seguir cria uma ordenação <code>coffees</code> com três elementos e o comprimento de três:</p> + +<pre class="eval deki-transform">var coffees = ["French Roast", "Colombian", "Kona"]; +</pre> + +<p><strong>Nota</strong> Uma ordenação literal é um tipo de inicializador de objeto. Veja<a href="/en/JavaScript/Guide/Working_with_Objects#Using_Object_Initializers" title="en/JavaScript/Guide/Working with Objects#Using Object Initializers"> Using Object Initializers</a> (en).</p> + +<p>Se uma ordenação é criada usando um literal em um alto nível de script, o JavaScript interpreta a ordenação cada vez que uma expressão contendo a ordenação literal é avaliada. Adicionalmente, um literal usado em uma função é criado cada vez que a função é chamada.</p> + +<p>Ordenações literais são também objetos <code>Array</code>. Veja <a href="/en/JavaScript/Guide/Predefined_Core_Objects#Array_Object" title="en/JavaScript/Guide/Predefined Core Objects#Array Object">Array Object</a> (en) para detalhes sobre objetos <code>Array</code>.</p> + +<h4 id="Vírgulas_extras_em_literais_ordenados">Vírgulas extras em literais ordenados</h4> + +<p>Não é necessário especificar todos os elementos de um literal ordenado. Se forem colocadas duas vírgulas em uma coluna, a ordenação é criada com espaços para elementos não especificados. O exemplo seguinte mostra a ordenação <code>fish</code>:</p> + +<pre class="eval deki-transform">var fish = ["Lion", , "Angel"]; +</pre> + +<p>Esta ordenação possui dois elementos com valores e um elemento vazio (<code>fish[0]</code> é "Lion", <code>fish[1]</code> é <code>undefined</code> e <code>fish[2]</code> é "Angel").</p> + +<p>Caso seja inserida uma última vírgula ao fim da lista de elementos, a vírgula é ignorada. No exemplo a seguir, o comprimento da ordenação é três. Não há <code>myList[3]</code>. Todas as outras vírgulas da lista indicam um novo elemento.</p> + +<pre class="eval deki-transform">var myList = ['home', , 'school', ]; +</pre> + +<p>No exemplo a seguir, o comprimento da ordenação é quatro, e <code>myList[0]</code> e <code>myList[2]</code> estão faltando.</p> + +<pre class="eval deki-transform">var myList = [ , 'home', , 'school']; +</pre> + +<p>No exemplo seguinte, o comprimento da ordenação é quatro, e <code>myList[1]</code> e <code>myList[3]</code> estão faltando. Somente a última vírgula é ignorada.</p> + +<pre class="eval deki-transform">var myList = ['home', , 'school', , ]; +</pre> + +<h3 id="Booleanos_literais"><a id="Booleanos literais" name="Booleanos literais">Booleanos literais</a></h3> + +<p>O tipo Booleano possui dois valores literais: <code>true</code> e <code>false</code>.</p> + +<p>Não confunda-os com os valores Booleanos primitivos <code>true</code> e <code>false</code> com os valores verdadeiro e falso do objeto Booleano. O objeto Booleano é um invólucro ao redor do tipo de dado Booleano. Veja <a href="/en/JavaScript/Guide/Predefined_Core_Objects#Boolean_Object" title="en/JavaScript/Guide/Predefined Core Objects#Boolean Object">Boolean Object</a> (en) para mais informações.</p> + +<h3 id="Inteiros_2"><a id="Inteiros" name="Inteiros">Inteiros</a></h3> + +<p>Inteiros podem ser expressos na base decimal (base 10), hexadecimal (base 16) e octal (base 8). Um inteiro decimal literal consiste em uma sequência de dígitos sem um 0 (zero) no início. Um 0 (zero) no início de um inteiro literal indica que se trata de um octal; um 0x (ou 0X) indica hexadecimal. Inteiros hexadecimais podem incluir dígitos (0-9) e as letras de a-f e A-F. Inteiros octais podem incluir somente dígitos 0-7.</p> + +<p>Inteiros octais literais são obsoletos e foram removidos do padrão ECMA-262, Edição 3. O JavaScript 1.5 ainda os suporta para compatibilidade com versões anteriores.</p> + +<p>Alguns exemplo de inteiros literais são:</p> + +<pre class="eval">0, 117 e -345 (decimal, base 10) +015, 0001 e -077 (octal, base 8) +0x1123, 0x00111 e -0xF1A7 (hexadecimal, "hex" ou base 16) +</pre> + +<h3 id="Pontos_flutuantes_literais"><a id="Pontos flutuantes literais" name="Pontos flutuantes literais">Pontos flutuantes literais</a></h3> + +<p>Um literal de ponto flutuante pode possuir as seguintes partes:</p> + +<ul> + <li>Um inteiro decimal, o qual pode ser assinado (precedido por "+" ou "-"),</li> + <li>Um ponto decimal ("."),</li> + <li>Uma fração (outro número decimal),</li> + <li>Um expoente.</li> +</ul> + +<p>A parte do expoente é um "e" ou "E" seguido por um inteiro, o qual pode ser assinado (precedido por "+" ou "-"). Um literal de ponto flutuante deve ter ao menos um dígito e um ponto decimal ou "e" (ou "E").</p> + +<p>Alguns exemplos de pontos flutuantes literais são 3.1415, -3.1E12, .1e12, and 2E-12.</p> + +<p>Mais claramente, a sintaxe é:</p> + +<pre class="eval">[digitos][.digitos][(E|e)[(+|-)]digitos] +</pre> + +<p>Por exemplo:</p> + +<pre class="eval">3.14 +2345.789 +.3333333333333333333 +</pre> + +<h3 id="Objetos_literais"><a id="Objetos literais" name="Objetos literais">Objetos literais</a></h3> + +<p>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.</p> + +<p>The following is an example of an object literal. The first element of the <code>car</code> object defines a property, <code>myCar</code>; the second element, the <code>getCar</code> property, invokes a function <code>(CarTypes("Honda"));</code> the third element, the <code>special</code> property, uses an existing variable (<code>Sales</code>).</p> + +<pre class="eval deki-transform">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 }; + +document.write(car.myCar); // Saturn +document.write(car.getCar); // Honda +document.write(car.special); // Toyota +</pre> + +<p>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.</p> + +<pre class="eval deki-transform">var car = { manyCars: {a: "Saab", "b": "Jeep"}, 7: "Mazda" }; + +document.write(car.manyCars.b); // Jeep +document.write(car[7]); // Mazda +</pre> + +<p>Please note:</p> + +<pre class="eval deki-transform">var foo = {a: "alpha", 2: "two"}; +document.write(foo.a); // alpha +document.write(foo[2]); // two +//document.write(foo.2); // Error: missing ) after argument list +//document.write(foo[a]); // Error: a is not defined +document.write(foo["a"]); // alpha +document.write(foo["2"]); // two +</pre> + +<h3 id="Strings_literais"><a id="Strings literais" name="Strings literais">Strings literais</a></h3> + +<p>A string literal is zero or more characters enclosed in double (<code>"</code>) or single (<code>'</code>) 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:</p> + +<ul> + <li><code>"foo"</code></li> + <li><code>'bar'</code></li> + <li><code>"1234"</code></li> + <li><code>"one line \n another line"</code></li> + <li><code>"John's cat"</code></li> +</ul> + +<p>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 <code>String.length</code> property with a string literal:</p> + +<pre class="deki-transform">"John's cat".length +</pre> + +<p>You should use string literals unless you specifically need to use a String object. See <a href="/en/JavaScript/Guide/Predefined_Core_Objects#String_Object" title="en/JavaScript/Guide/Predefined Core Objects#String Object">String Object</a> for details on <code>String</code> objects.</p> + +<h4 id="Usando_caracteres_especiais_em_strings">Usando caracteres especiais em strings</h4> + +<p>In addition to ordinary characters, you can also include special characters in strings, as shown in the following example.</p> + +<pre class="eval deki-transform">"one line \n another line" +</pre> + +<p>The following table lists the special characters that you can use in JavaScript strings.</p> + +<table class="standard-table"> + <caption>Table 2.1 JavaScript special characters</caption> + <thead> + <tr> + <th scope="col">Character</th> + <th scope="col">Meaning</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>\b</code></td> + <td>Backspace</td> + </tr> + <tr> + <td><code>\f</code></td> + <td>Form feed</td> + </tr> + <tr> + <td><code>\n</code></td> + <td>New line</td> + </tr> + <tr> + <td><code>\r</code></td> + <td>Carriage return</td> + </tr> + <tr> + <td><code>\t</code></td> + <td>Tab</td> + </tr> + <tr> + <td><code>\v</code></td> + <td>Vertical tab</td> + </tr> + <tr> + <td><code>\'</code></td> + <td>Apostrophe or single quote</td> + </tr> + <tr> + <td><code>\"</code></td> + <td>Double quote</td> + </tr> + <tr> + <td><code>\\</code></td> + <td>Backslash character (\).</td> + </tr> + <tr> + <td><code>\<em>XXX</em></code></td> + <td>The character with the Latin-1 encoding specified by up to three octal digits <em>XXX</em> between 0 and 377. For example, \251 is the octal sequence for the copyright symbol.</td> + </tr> + <tr> + <td><code>\x<em>XX</em></code></td> + <td>The character with the Latin-1 encoding specified by the two hexadecimal digits <em>XX</em> between 00 and FF. For example, \xA9 is the hexadecimal sequence for the copyright symbol.</td> + </tr> + <tr> + <td><code>\u<em>XXXX</em></code></td> + <td>The Unicode character specified by the four hexadecimal digits <em>XXXX</em>. For example, \u00A9 is the Unicode sequence for the copyright symbol. See <a href="#Sequências de escape em Unicode">Unicode Escape Sequences</a>.</td> + </tr> + </tbody> +</table> + +<h4 id="Caracteres_de_escape">Caracteres de escape</h4> + +<p>For characters not listed in Table 2.1, a preceding backslash is ignored, but this usage is deprecated and should be avoided.</p> + +<p>You can insert a quotation mark inside a string by preceding it with a backslash. This is known as <em>escaping</em> the quotation mark. For example:</p> + +<pre class="eval deki-transform">var quote = "He read \"The Cremation of Sam McGee\" by R.W. Service."; +document.write(quote); +</pre> + +<p>The result of this would be:</p> + +<pre class="eval">He read "The Cremation of Sam McGee" by R.W. Service. +</pre> + +<p>To include a literal backslash inside a string, you must escape the backslash character. For example, to assign the file path <code>c:\temp</code> to a string, use the following:</p> + +<pre class="eval deki-transform">var home = "c:\\temp"; +</pre> + +<p>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.</p> + +<pre>var str = "this string \ +is broken \ +across multiple\ +lines."</pre> + +<p>Although JavaScript does not have "heredoc" syntax, you can get close by adding a linebreak escape and an escaped linebreak at the end of each line:</p> + +<pre>var poem = +"Roses are red,\n\ +Violets are blue.\n\ +I'm schizophrenic,\n\ +And so am I." +</pre> + +<h2 id="Unicode">Unicode</h2> + +<p>Unicode is a universal character-coding standard for the interchange and display of principal written languages. It covers the languages of the Americas, Europe, Middle East, Africa, India, Asia, and Pacifica, as well as historic scripts and technical symbols. Unicode allows for the exchange, processing, and display of multilingual texts, as well as the use of common technical and mathematical symbols. It hopes to resolve internationalization problems of multilingual computing, such as different national character standards. Not all modern or archaic scripts, however, are currently supported.</p> + +<p>The Unicode character set can be used for all known encoding. Unicode is modeled after the ASCII (American Standard Code for Information Interchange) character set. It uses a numerical value and name for each character. The character encoding specifies the identity of the character and its numeric value (code position), as well as the representation of this value in bits. The 16-bit numeric value (code value) is defined by a hexadecimal number and a prefix U, for example, U+0041 represents A. The unique name for this value is LATIN CAPITAL LETTER A.</p> + +<p><strong>Unicode is not supported in versions of JavaScript prior to 1.3.</strong></p> + +<h3 id="Compatibilidade_do_Unicode_com_ASCII_e_ISO">Compatibilidade do Unicode com ASCII e ISO</h3> + +<p>Unicode is fully compatible with the International Standard ISO/IEC 10646-1; 1993, which is a subset of ISO 10646.</p> + +<p>Several encoding standards (including UTF-8, UTF-16 and ISO UCS-2) are used to physically represent Unicode as actual bits.</p> + +<p>The UTF-8 encoding of Unicode is compatible with ASCII characters and is supported by many programs. The first 128 Unicode characters correspond to the ASCII characters and have the same byte value. The Unicode characters U+0020 through U+007E are equivalent to the ASCII characters 0x20 through 0x7E. Unlike ASCII, which supports the Latin alphabet and uses a 7-bit character set, UTF-8 uses between one and four octets for each character ("octet" meaning a byte, or 8 bits.) This allows for several million characters. An alternative encoding standard, UTF-16, uses two octets to represent Unicode characters. An escape sequence allows UTF-16 to represent the whole Unicode range by using four octets. The ISO UCS-2 (Universal Character Set) uses two octets.</p> + +<p>JavaScript and Navigator support for UTF-8/Unicode means you can use non-Latin, international, and localized characters, plus special technical symbols in JavaScript programs. Unicode provides a standard way to encode multilingual text. Since the UTF-8 encoding of Unicode is compatible with ASCII, programs can use ASCII characters. You can use non-ASCII Unicode characters in the comments, string literals, identifiers, and regular expressions of JavaScript.</p> + +<h3 id="Sequências_de_escape_em_Unicode"><a id="Sequências de escape em Unicode" name="Sequências de escape em Unicode">Sequências de escape em Unicode</a></h3> + +<p>You can use the Unicode escape sequence in string literals, regular expressions, and identifiers. The escape sequence consists of six ASCII characters: \u and a four-digit hexadecimal number. For example, \u00A9 represents the copyright symbol. Every Unicode escape sequence in JavaScript is interpreted as one character.</p> + +<p>The following code returns the copyright symbol and the string "Netscape Communications".</p> + +<pre class="deki-transform">var x = "\u00A9 Netscape Communications";</pre> + +<p>The following table lists frequently used special characters and their Unicode value.</p> + +<table class="standard-table"> + <caption>Table 2.2 Unicode values for special characters</caption> + <thead> + <tr> + <th scope="col">Category</th> + <th scope="col">Unicode value</th> + <th scope="col">Name</th> + <th scope="col">Format name</th> + </tr> + </thead> + <tbody> + <tr> + <td rowspan="4">White space values<br> + <br> + <br> + </td> + <td>\u0009</td> + <td>Tab</td> + <td><TAB></td> + </tr> + <tr> + <td>\u000B</td> + <td>Vertical Tab</td> + <td><VT></td> + </tr> + <tr> + <td>\u000C</td> + <td>Form Feed</td> + <td><FF></td> + </tr> + <tr> + <td>\u0020</td> + <td>Space</td> + <td><SP></td> + </tr> + <tr> + <td rowspan="2">Line terminator values<br> + </td> + <td>\u000A</td> + <td>Line Feed</td> + <td><LF></td> + </tr> + <tr> + <td>\u000D</td> + <td>Carriage Return</td> + <td><CR></td> + </tr> + <tr> + <td rowspan="5">Additional Unicode escape sequence values<br> + <br> + <br> + <br> + </td> + <td>\u0008</td> + <td>Backspace</td> + <td><BS></td> + </tr> + <tr> + <td>\u0009</td> + <td>Horizontal Tab</td> + <td><HT></td> + </tr> + <tr> + <td>\u0022</td> + <td>Double Quote</td> + <td>"</td> + </tr> + <tr> + <td>\u0027</td> + <td>Single Quote</td> + <td>'</td> + </tr> + <tr> + <td>\u005C</td> + <td>Backslash</td> + <td>\</td> + </tr> + </tbody> +</table> + +<p>The JavaScript use of the Unicode escape sequence is different from Java. In JavaScript, the escape sequence is never interpreted as a special character first. For example, a line terminator escape sequence inside a string does not terminate the string before it is interpreted by the function. JavaScript ignores any escape sequence if it is used in comments. In Java, if an escape sequence is used in a single comment line, it is interpreted as an Unicode character. For a string literal, the Java compiler interprets the escape sequences first. For example, if a line terminator escape character (e.g., \u000A) is used in Java, it terminates the string literal. In Java, this leads to an error, because line terminators are not allowed in string literals. You must use \n for a line feed in a string literal. In JavaScript, the escape sequence works the same way as \n.</p> + +<h3 id="Caracteres_Unicode_em_arquivos_JavaScript">Caracteres Unicode em arquivos JavaScript</h3> + +<p>Earlier versions of <a href="/en/Gecko" title="en/Gecko">Gecko</a> assumed the Latin-1 character encoding for JavaScript files loaded from XUL. Starting with Gecko 1.8, the character encoding is inferred from the XUL file's encoding. Please see <a href="/en/International_characters_in_XUL_JavaScript" title="en/International_characters_in_XUL_JavaScript">International characters in XUL JavaScript</a> for more information.</p> + +<h3 id="Exibindo_caracteres_com_Unicode">Exibindo caracteres com Unicode</h3> + +<p>You can use Unicode to display the characters in different languages or technical symbols. For characters to be displayed properly, a client such as Mozilla Firefox or Netscape needs to support Unicode. Moreover, an appropriate Unicode font must be available to the client, and the client platform must support Unicode. Often, Unicode fonts do not display all the Unicode characters. Some platforms, such as Windows 95, provide partial support for Unicode.</p> + +<p>To receive non-ASCII character input, the client needs to send the input as Unicode. Using a standard enhanced keyboard, the client cannot easily input the additional characters supported by Unicode. Sometimes, the only way to input Unicode characters is by using Unicode escape sequences.</p> + +<p>For more information on Unicode, see the <a class="external" href="http://www.unicode.org/">Unicode Home Page</a> and The Unicode Standard, Version 2.0, published by Addison-Wesley, 1996.</p> + +<pre class="script" style="font-size: 16px;">autoPreviousNext("JSGChapters");</pre> diff --git a/files/pt-pt/web/javascript/index.html b/files/pt-pt/web/javascript/index.html new file mode 100644 index 0000000000..96b6b4b28b --- /dev/null +++ b/files/pt-pt/web/javascript/index.html @@ -0,0 +1,140 @@ +--- +title: JavaScript +slug: Web/JavaScript +tags: + - Aprender + - JavaScript + - Landing + - Página Landing + - 'l10n:priority' +translation_of: Web/JavaScript +--- +<div>{{JsSidebar}}</div> + +<div> +<p class="summary"><strong>JavaScript</strong> (<strong>JS</strong>) é uma linguagem de programação compilada simples, interpretada ou "<em>just-in-time"</em> com {{Glossary("First-class Function", "funções de primeira classe")}}. Embora seja mais conhecida coma a linguagem de <em>scripting</em> para as páginas da Web, também é utilizada em <a class="external" href="https://en.wikipedia.org/wiki/JavaScript#Uses_outside_Web_pages">muitos ambientes além de navegadores</a> (inglês), tais como <a class="external" href="/en-US/docs/Glossary/Node.js">Node.js</a>, <a href="https://couchdb.apache.org/">Apache CouchDB</a> e <a href="http://www.adobe.com/devnet/acrobat/javascript.html">Adobe Acrobat</a>. 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 <a href="/pt-PT/docs/Web/JavaScript/Sobre_JavaScript">sobre o JavaScript</a>.</p> + +<p>Esta secção do <em>site </em>é 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 <a href="/pt-PT/docs/Web/API">APIs da Web </a>e <a href="/pt-PT/docs/DOM/DOM_Reference" title="https://developer.mozilla.org/en/DOM">DOM</a>.</p> + +<p>O padrão para JavaScript é <a href="/en-US/docs/Web/JavaScript/Language_Resources">ECMAScript</a>. Em 2012, todos os <a href="https://kangax.github.io/compat-table/es5/">navegadores modernos</a> 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, <a href="https://www.ecma-international.org">ECMA International</a> 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 é <a href="https://tc39.github.io/ecma262/">ECMAScript 2018</a>.</p> + +<p>Não faça confusão entre JavaScript e <a href="https://pt.wikipedia.org/wiki/Java_(linguagem_de_programa%C3%A7%C3%A3o)">a linguagem de programação Java</a>. 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.</p> + +<div class="column-container"> +<div class="column-half"> +<h2 id="Tutoriais">Tutoriais</h2> + +<p>Aprender a programar em JavaScript com guias e tutorials.</p> + +<h3 id="Para_principiantes_absolutos">Para principiantes absolutos</h3> + +<p>Dirija-se ao nosso <a href="/en-US/docs/Learn/JavaScript">tópico sobre JavaScript</a> se quer aprender esta linguagem mas não tem experiência alguma em programação. Seguem-se os módulos disponíveis:</p> + +<dl> + <dt><a href="/pt-PT/docs/Learn/JavaScript/Primeiros_passos">JavaScript - primeiros passos</a></dt> + <dd>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.</dd> + <dt><a href="/pt-PT/docs/Learn/JavaScript/Elementos_constituintes">JavaScript - elementos constituintes</a></dt> + <dd>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.</dd> + <dt><a href="https://wiki.developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects">Introducing JavaScript objects</a></dt> + <dd>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.</dd> + <dt><a href="https://wiki.developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous">Asynchronous JavaScript</a></dt> + <dd>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.</dd> + <dt><a href="https://wiki.developer.mozilla.org/en-US/docs/Learn/JavaScript/Client-side_web_APIs">Client-side web APIs</a></dt> + <dd>Explores what APIs are, and how to use some of the most common APIs you'll come across often in your development work.</dd> +</dl> + +<h3 id="Guia_de_JavaScript">Guia de JavaScript</h3> + +<dl> + <dt><a href="/pt-PT/docs/Web/JavaScript/Guia">Guia de JavaScript</a></dt> + <dd>Um guia muito detalhado de JavaScript, apropriado para pessoas com experiência em JavaScript ou noutra linguagem.</dd> +</dl> + +<h3 id="Intermediário">Intermediário</h3> + +<dl> + <dt><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript">Reintrodução ao JavaScript</a></dt> + <dd>Uma visão geral para quem acha que conhece o JavaScript.</dd> +</dl> + +<dl> + <dt><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures">Estrutura de Dados no JavaScript</a></dt> + <dd>Uma visão geral das estruturas de dados disponíveis no JavaScript.</dd> + <dt><a href="/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness">Equality comparisons and sameness</a></dt> + <dd>JavaScript provides three different value-comparison operations: strict equality using <code>===</code>, loose equality using <code>==</code>, and the {{jsxref("Global_Objects/Object/is", "Object.is()")}} method.</dd> + <dt><a href="https://wiki.developer.mozilla.org/en-US/docs/Web/JavaScript/Closures">Closures</a></dt> + <dd> + <p>A closure is the combination of a function and the lexical environment within which that function was declared.</p> + </dd> +</dl> + +<h3 id="Avançado">Avançado</h3> + +<dl> + <dt><a href="/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain">Inheritance and the prototype chain</a></dt> + <dd>Explanation of the widely misunderstood and under-estimated prototype-based inheritance.</dd> + <dt><a href="/en-US/docs/Web/JavaScript/Reference/Strict_mode">Strict mode</a></dt> + <dd>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.</dd> + <dt><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays">JavaScript typed arrays</a></dt> + <dd>JavaScript typed arrays provide a mechanism for accessing raw binary data.</dd> + <dt><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Memory_Management">Memory Management</a></dt> + <dd>Memory life cycle and garbage collection in JavaScript.</dd> + <dt><a href="/en-US/docs/Web/JavaScript/EventLoop">Concurrency model and Event Loop</a></dt> + <dd>JavaScript has a concurrency model based on an "event loop".</dd> +</dl> +</div> + +<div class="column-half"> +<h2 id="Referência">Referência</h2> + +<p>Explore a documentação completa de <a href="/pt-PT/docs/Web/JavaScript/Reference">refrência de JavaScript</a>.</p> + +<dl> + <dt><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects">Standard objects</a></dt> + <dd>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.</dd> + <dt><a href="/en-US/docs/Web/JavaScript/Reference/Operators">Expressions and operators</a></dt> + <dd>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 <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence">operator precedence</a>, and more.</dd> + <dt><a href="/en-US/docs/Web/JavaScript/Reference/Statements">Statements and declarations</a></dt> + <dd>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.</dd> + <dt><a href="/en-US/docs/Web/JavaScript/Reference/Functions">Funções</a></dt> + <dd>Aprenda como trabalhar com funções do JavaScript para desenvolver suas aplicações.</dd> +</dl> + +<h2 id="Ferramentas_e_recursos">Ferramentas e recursos</h2> + +<p>Ferramentas úteis para escrever e depurar o seu código <strong>JavaScript</strong>.</p> + +<dl> + <dt><a href="/pt-PT/docs/Tools">Ferramentas de Desenvolvimento do Firefox</a></dt> + <dd><a href="/pt-PT/docs/Tools/Scratchpad">Scratchpad</a>, <a href="/pt-PT/docs/Tools/Consola_da_Web">Consola da Web</a>, <a href="/pt-PT/docs/Tools/Desempenho">JavaScript Profiler</a>, <a href="/en-US/docs/Tools/Debugger">Debugger</a>, e muito mais.</dd> + <dt><a href="/en-US/docs/Web/JavaScript/Shells">JavaScript Shells</a></dt> + <dd>A JavaScript shell allows you to quickly test snippets of JavaScript code.</dd> + <dt><a href="https://learnjavascript.online/">Learn JavaScript</a></dt> + <dd>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.</dd> + <dt><a href="https://togetherjs.com/">TogetherJS</a></dt> + <dd>Collaboration made easy. By adding TogetherJS to your site, your users can help each other out on a website in real time!</dd> + <dt><a href="https://stackoverflow.com/questions/tagged/javascript">Stack Overflow</a></dt> + <dd>Dúvidas no Stack Overflow marcadas com "JavaScript".</dd> + <dt><a href="/en-US/docs/Web/JavaScript/New_in_JavaScript">JavaScript versions and release notes</a></dt> + <dd>Browse JavaScript's feature history and implementation status.</dd> + <dt><a href="https://jsfiddle.net/">JSFiddle</a></dt> + <dd>Edit JavaScript, CSS, HTML and get live results. Use external resources and collaborate with your team online.</dd> + <dt></dt> + <dt><a href="https://plnkr.co/">Plunker</a></dt> + <dd>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.</dd> + <dt><a href="https://jsbin.com/">JSBin</a></dt> + <dd> + <p>JS Bin is an open source collaborative web development debugging tool.</p> + </dd> + <dt><a href="https://codepen.io/">Codepen</a></dt> + <dd> + <p>Codepen is another collaborative web development tool used as a live result playground.</p> + </dd> + <dt><a href="https://stackblitz.com/">StackBlitz</a></dt> + <dd> + <p>StackBlitz is another online playground/debugging tool, which can host and deploy full stack applications using React, Angular, etc.</p> + </dd> +</dl> +</div> +</div> +</div> diff --git a/files/pt-pt/web/javascript/novidades_no_javascript/index.html b/files/pt-pt/web/javascript/novidades_no_javascript/index.html new file mode 100644 index 0000000000..42d40e9929 --- /dev/null +++ b/files/pt-pt/web/javascript/novidades_no_javascript/index.html @@ -0,0 +1,80 @@ +--- +title: Novidades no JavaScript +slug: Web/JavaScript/Novidades_no_JavaScript +tags: + - NeedsTranslation + - TopicStub +translation_of: Archive/Web/JavaScript/New_in_JavaScript +--- +<div>{{jsSidebar("New_in_JS")}}</div> + +<p>This chapter contains information about JavaScript's version history and implementation status for Mozilla/SpiderMonkey-based JavaScript applications, such as Firefox.</p> + +<h2 id="ECMAScript_versions">ECMAScript versions</h2> + +<dl> + <dt><a href="/en-US/docs/Web/JavaScript/Language_Resources">Language resources</a></dt> + <dd>Learn more about the ECMAScript standards on which the JavaScript language is based on.</dd> + <dt><a href="/en-US/docs/Web/JavaScript/New_in_JavaScript/ECMAScript_5_support_in_Mozilla">ECMAScript 5 support</a></dt> + <dd>Implementation status for the current standard ECMA-262 Edition 5.1 in Mozilla-based engines and products.</dd> + <dt><a href="/en-US/docs/Web/JavaScript/New_in_JavaScript/ECMAScript_6_support_in_Mozilla">ECMAScript 6 support</a></dt> + <dd>Implementation status for the draft ECMA-262 Edition 6 in Mozilla-based engines and products.</dd> + <dt><a href="/en-US/docs/Web/JavaScript/New_in_JavaScript/ECMAScript_7_support_in_Mozilla">ECMAScript 7 support</a></dt> + <dd>Implementation status for the upcoming ECMA-262 Edition 7 in Mozilla-based engines and products.</dd> +</dl> + +<h2 id="JavaScript_release_notes">JavaScript release notes</h2> + +<dl> + <dt><a href="/en-US/docs/Web/JavaScript/New_in_JavaScript/Firefox_JavaScript_changelog">Firefox JavaScript changelog</a></dt> + <dd>See this changelog for JavaScript features implemented in Firefox 5 and later.</dd> + <dt>Chrome JavaScript changelog</dt> + <dd>(TODO). See this changelog for JavaScript features implemented in Chrome releases.</dd> +</dl> + +<h2 id="JavaScript_versions">JavaScript versions</h2> + +<p><strong>Deprecated</strong> ({{deprecated_inline()}}). The explicit versioning and opt-in of language features was Mozilla-specific and <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=867609">is in process of being removed</a>. Firefox 4 was the last version which referred to an JavaScript version (1.8.5). With new ECMA standards, JavaScript language features are now often mentioned with their initial definition in ECMA-262 Editions such as Edition 6 (ES6).</p> + +<p>JavaScript was released as version 1.0 in March 1996 in Netscape Navigator 2.0 and Internet Explorer 2.0.</p> + +<dl> + <dt><a href="/en-US/docs/Web/JavaScript/New_in_JavaScript/1.1">JavaScript 1.1</a></dt> + <dd>Version shipped in Netscape Navigator 3.0. Released on August 19, 1996.</dd> + <dt><a href="/en-US/docs/Web/JavaScript/New_in_JavaScript/1.2">JavaScript 1.2</a></dt> + <dd>Version shipped in Netscape Navigator 4.0-4.05. Released on June 11, 1997.</dd> + <dt><a href="/en-US/docs/Web/JavaScript/New_in_JavaScript/1.3">JavaScript 1.3</a></dt> + <dd>Version shipped in Netscape Navigator 4.06-4.7x. Released on October 19, 1998.<br> + Standardization work to be compliant with ECMA-262 1st and 2nd Edition.</dd> + <dt><a href="/en-US/docs/Web/JavaScript/New_in_JavaScript/1.4">JavaScript 1.4</a></dt> + <dd>Version shipped in Netscape's server side JavaScript. Released in 1999.</dd> + <dt><a href="/en-US/docs/Web/JavaScript/New_in_JavaScript/1.5">JavaScript 1.5</a></dt> + <dd>Version shipped in Netscape Navigator 6.0 and Firefox 1.0. Release on November 14, 2000.<br> + Standardization work to be compliant with ECMA-262 3rd Edition.</dd> + <dt><a href="/en-US/docs/Web/JavaScript/New_in_JavaScript/1.6">JavaScript 1.6</a></dt> + <dd>Version shipped in Firefox 1.5. Released in November 2005.<br> + Includes ECMAScript for XML (E4X), new <code>Array</code> methods plus <code>String</code> and <code>Array</code> generics.</dd> + <dt><a href="/en-US/docs/Web/JavaScript/New_in_JavaScript/1.7">JavaScript 1.7</a></dt> + <dd>Version shipped in Firefox 2. Released in October 2006.<br> + Includes generators, iterators, array comprehensions, <code>let</code> expressions, and destructuring assignment.</dd> + <dt><a href="/en-US/docs/Web/JavaScript/New_in_JavaScript/1.8">JavaScript 1.8</a></dt> + <dd>Version shipped in Firefox 3. Released in June 2008.<br> + Includes expression closures, generator expressions and <code>Array.reduce()</code></dd> + <dt><a href="/en-US/docs/Web/JavaScript/New_in_JavaScript/1.8.1">JavaScript 1.8.1</a></dt> + <dd>Version shipped in Firefox 3.5. Released on <span class="st">June 30, 2009.<br> + Includes the TraceMonkey JIT and supports native JSON.</span></dd> + <dt>JavaScript 1.8.2</dt> + <dd>Version shipped in Firefox 3.6. Released June 22, 2009.<br> + Includes only minor changes.</dd> + <dt><a href="/en-US/docs/Web/JavaScript/New_in_JavaScript/1.8.5">JavaScript 1.8.5</a></dt> + <dd>Version shipped in Firefox 4. Released July 27, 2010.<br> + Includes many new features for ECMA-262 Edition 5 compliance.<br> + This is the last JavaScript version.</dd> +</dl> + +<h2 id="Features_still_requiring_version_opt-in">Features still requiring version opt-in</h2> + +<dl> + <dt><a href="/en-US/docs/Web/JavaScript/Reference/Statements/let"><code>let</code> statement</a></dt> + <dd>The <code>let</code> statement requires the JavaScript version 1.7 (or higher) opt-in. See {{bug(932517)}} and {{bug(932513)}}.</dd> +</dl> diff --git a/files/pt-pt/web/javascript/novidades_no_javascript/novidades_no_javascript_1.8/index.html b/files/pt-pt/web/javascript/novidades_no_javascript/novidades_no_javascript_1.8/index.html new file mode 100644 index 0000000000..4791e4d0e9 --- /dev/null +++ b/files/pt-pt/web/javascript/novidades_no_javascript/novidades_no_javascript_1.8/index.html @@ -0,0 +1,136 @@ +--- +title: Novidades no Javascript 1.8 +slug: Web/JavaScript/Novidades_no_JavaScript/Novidades_no_Javascript_1.8 +tags: + - JavaScript + - Todas_as_Categorias +translation_of: Archive/Web/JavaScript/New_in_JavaScript/1.8 +--- +<p>{{jsSidebar("New_in_JS")}}</p> + +<p>O JavaScript 1.8 está programado para ser lançado como parte do Gecko 1.9 (que será incorporado ao <a href="/pt/Firefox_3_para_desenvolvedores" title="pt/Firefox_3_para_desenvolvedores">Firefox 3</a>). Esta é uma atualização menos substancial que o <a href="/en/New_in_JavaScript_1.7">JavaScript 1.7</a>, mas tem algumas atualizações para acompanhar o progresso rumo ao ECMAScript 4/JavaScript 2. Esta liberação incluirá todas as novas características especificadas no <a href="/en/New_in_JavaScript_1.6">JavaScript 1.6</a> e <a href="/en/New_in_JavaScript_1.7">JavaScript 1.7</a>.</p> + +<p>Veja o {{ Bug(380236) }} para acompanhar o progresso do desenvolvimento do JavaScript 1.8.</p> + +<h2 id="Usando_JavaScript_1.8" name="Usando_JavaScript_1.8">Usando JavaScript 1.8</h2> + +<p>A fim de usar algumas das novas características do JavaScript 1.8 no HTML, use:</p> + +<pre class="eval"> <script type="application/javascript;version=1.8"> ... seu código ... </script> +</pre> + +<p>Quando usando o <a href="/en/Introduction_to_the_JavaScript_shell">JavaScript shell</a>, componentes XPCOM ou elementos XUL <code><script></code>, a versão mais recente do Javascript (1.8 no Mozilla 1.9) é usada automaticamente ({{ Bug(381031) }}, {{ Bug(385159) }}).</p> + +<p>Os recursos que requerem o uso das novas palavras-chave "yield" e "let" requerem que você especifique a versão 1.7 ou mais recente, porque o código existente pode usar estas palavras-chave como variáveis ou nomes de função. Os recursos que não introduzem novas palavras-chave (como o gerador de expressões) podem ser usados sem que seja necessário especificar a versão do JavaScript.</p> + +<h2 id="Fechamentos_de_express.C3.B5es" name="Fechamentos_de_express.C3.B5es">Fechamentos de expressões</h2> + +<p>Esta adição nada mais é que uma abreviação para escrever funções simples, dando à linguagem algo similar a uma típica <a class="external" href="http://en.wikipedia.org/wiki/Lambda_calculus#Lambda_calculus_and_programming_languages">notação lambda</a>.</p> + +<p>JavaScript 1.7 e mais antigos:</p> + +<pre class="eval"> function(x) { return x * x; } +</pre> + +<p>JavaScript 1.8:</p> + +<pre class="eval"> function(x) x * x +</pre> + +<p>Esta sintaxe permite que você deixe de fora as chaves e a declaração 'return' — fazendo-as implícitas. Não há benefício adicionado ao se escrever código desta maneira, à exceção de ser sintaticamente mais curto.</p> + +<p><strong>Exemplos:</strong></p> + +<p>Uma abreviação para ligar ouvintes de evento:</p> + +<pre class="eval"> document.addEventListener("click", function() false, true); +</pre> + +<p>Usando esta notação com alguma das funções de array do JavaScript 1.6:</p> + +<pre class="eval"> elems.some(function(elem) elem.type == "text"); +</pre> + +<h2 id="Gerador_de_express.C3.B5es" name="Gerador_de_express.C3.B5es">Gerador de expressões</h2> + +<p>Esta adição permite que você crie geradores de maneira simples (que foram introduzidos no JavaScript 1.7). Tipicamente você teria que criar uma função personalizada contendo a palavra-chave yield, mas esta adição permite que você use uma sintaxe semelhante à compreensão de arrays para criar uma instrução geradora idêntica.</p> + +<p>No JavaScript 1.7, você poderia escrever algo como o seguinte, a fim de criar um gerador personalizado para um objeto:</p> + +<pre class="eval"> function add3(obj) { + for ( let i in obj ) + yield i + 3; + } + + let it = add3(someObj); + try { + while (true) { + document.write(it.next() + "<br>\n"); + } + } catch (err if err instanceof StopIteration) { + document.write("End of record.<br>\n"); + } +</pre> + +<p>No JavaScript 1.8, você pode contornar a criação de uma função de gerador personalizada usando um gerador de expressões em vez disso:</p> + +<pre class="eval"> let it = (i + 3 for (i in someObj)); + try { + while (true) { + document.write(it.next() + "<br>\n"); + } + } catch (err if err instanceof StopIteration) { + document.write("End of record.<br>\n"); + } +</pre> + +<p>Geradores de expressões também podem ser passados como valores a uma função. Isto é particularmente notável de modo que geradores não serão executados antes que seja absolutamente necessário (diferente de típicas situações de compreensão de array, onde os arrays são construídos antes do tempo). Um exemplo da diferença pode ser visto aqui:</p> + +<p>Usando a compreensão de array do JavaScript 1.7</p> + +<pre class="eval"> handleResults([ i for ( i in obj ) if ( i > 3 ) ]); + + function handleResults( results ) { + for ( let i in results ) + // ... + } +</pre> + +<p>Usando o gerador de expressões do JavaScript 1.8</p> + +<pre class="eval"> handleResults( i for ( i in obj ) if ( i > 3 ) ); + + function handleResults( results ) { + for ( let i in results ) + // ... + } +</pre> + +<p>A diferença significativa entre os dois exemplos, começando pelo que usa o gerador de expressões, é que você poderia usar somente o <em>loop</em> uma vez sobre a estrutura 'obj', ao invés de uma vez compreender o array e novamente iterar com ele.</p> + +<h2 id="Mais_extras_do_Array" name="Mais_extras_do_Array">Mais extras do Array</h2> + +<p>Existem dois novos métodos iterativos de <code><a href="/en/Core_JavaScript_1.5_Reference/Global_Objects/Array">Array</a></code> incluídos no JavaScript 1.8, especificamente:</p> + +<ul> + <li><code><a href="/en/Core_JavaScript_1.5_Reference/Objects/Array/reduce">reduce()</a></code> - executa uma função em cada item no <em>array</em> e coleta os resultados de chamadas anteriores.</li> + <li><code><a href="/en/Core_JavaScript_1.5_Reference/Objects/Array/reduceRight">reduceRight()</a></code> - executa uma função em cada item no <em>array</em> e coleta os resultados de chamadas anteriores, mas em reverso.</li> +</ul> + +<h2 id="Mudan.C3.A7as_na_desestrutura.C3.A7.C3.A3o_for..in" name="Mudan.C3.A7as_na_desestrutura.C3.A7.C3.A3o_for..in">Mudanças na desestruturação for..in</h2> + +<p>Menção em <a href="/en/New_in_JavaScript_1.7#Looping_across_objects">en:New_in_JavaScript_1.7#Looping_across_objects</a> ({{ Bug(366941) }}).</p> + +<h2 id="Mudan.C3.A7as_iminentes" name="Mudan.C3.A7as_iminentes">Mudanças iminentes</h2> + +<p>As mudanças esperadas para a chegada no JavaScript 1.8 incluem:</p> + +<ul> + <li>Codificação e decodificação JSON.</li> + <li>Sintaxe <em>slice</em>.</li> + <li>Desestruturação generalizada <code>for...in</code> (isso significa algo diferente de <a href="#Chances_in_destrugturing_for..in">#Chances in destrugturing for..in</a>? --<a href="/User:Nickolay">Nickolay</a> 10:52, 9 de setembro de 2007 (PDT)).</li> +</ul> + +<p><span class="comment">Categorias</span></p> + +<p><span class="comment">Interwiki Language Links</span></p> diff --git a/files/pt-pt/web/javascript/o_que_é_o_javascript/index.html b/files/pt-pt/web/javascript/o_que_é_o_javascript/index.html new file mode 100644 index 0000000000..4145f9dc58 --- /dev/null +++ b/files/pt-pt/web/javascript/o_que_é_o_javascript/index.html @@ -0,0 +1,13 @@ +--- +title: O que é o JavaScript +slug: Web/JavaScript/O_que_é_o_JavaScript +--- +<p>O JavaScript é uma linguagem de programação do lado <b>cliente</b>, ou seja, é processada pelo próprio navegador. +Com o JavaScript podemos criar efeitos especiais para nossas páginas na Web, além +de podermos proporcionar uma maior interatividade com nossos usuários. +O JavaScript é uma linguagem orientada a objetos, ou seja, ela trata todos os elementos da página +como objetos distintos, fascilitando a tarefa da programação. +</p><p>Resumindo, o JavaScript é uma poderosa linguagem que deve ser dominada por quem deseja criar páginas Web dinamicas e interativas. +</p><p><br> +--<a>rafael.marcondes92@gmail.com</a> 12:39, 14 Julho 2008 (PDT) +</p> diff --git a/files/pt-pt/web/javascript/reference/classes/index.html b/files/pt-pt/web/javascript/reference/classes/index.html new file mode 100644 index 0000000000..03ff413025 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/classes/index.html @@ -0,0 +1,437 @@ +--- +title: Classes +slug: Web/JavaScript/Reference/Classes +tags: + - Classes + - Construtores + - ECMAScript 2015 + - Herança + - Intermedio + - JavaScript +translation_of: Web/JavaScript/Reference/Classes +--- +<div>{{JsSidebar("Classes")}}</div> + +<p>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 <strong>não </strong>introduz no JavaScript nenhum novo modelo de herança do paradigma das linguagens orientado a objetos .</p> + +<h2 id="Definição_de_classes">Definição de classes</h2> + +<p>As classes são na realidade "<a href="/en-US/docs/Web/JavaScript/Reference/Functions">funções</a> especiais", e, tal como você pode definir o <a href="/en-US/docs/Web/JavaScript/Reference/Operators/function">expressões de funções</a> e <a href="/en-US/docs/Web/JavaScript/Reference/Statements/function">declarações de funções</a>, a sintaxe de classe tem dois componentes: <a href="/en-US/docs/Web/JavaScript/Reference/Operators/class">expressões de classes</a> e a <a href="/en-US/docs/Web/JavaScript/Reference/Statements/class">declaração da classe</a>.</p> + +<h3 id="Declaração_de_classes">Declaração de classes</h3> + +<p>Uma forma de definir uma classe é usar uma <strong>declaração de classe</strong>. Para declarar uma classe, utiliza-se a palavra reservada <code>class</code> seguida do nome da classe ("Rectangle" no seguinte exemplo).</p> + +<pre class="brush: js">class Rectangle { + constructor(height, width) { + this.height = height; + this.width = width; + } +}</pre> + +<h4 id="Hoisting">Hoisting</h4> + +<p>Uma diferença importante entre a <strong>declaração de funções</strong> e a <strong>declaração de classes</strong> é 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")}}:</p> + +<pre class="brush: js example-bad">var p = new Rectangle(); // ReferenceError + +class Rectangle {} +</pre> + +<h3 id="Expressão_de_Classe">Expressão de Classe</h3> + +<p>A <strong>expressão de classe</strong> é 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 <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name">.name</a> da classe (não da instância) )</p> + +<pre class="brush: js">// 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; + } +}; +</pre> + +<div class="blockIndicator note"> +<p><strong>Nota:</strong> <strong>Expressões </strong>de classes também padecem da mesma situação de hoisting mencionada para as <strong>declarações </strong>de classes.</p> +</div> + +<h2 id="Definição_de_corpo_de_classe_e_de_método">Definição de corpo de classe e de método</h2> + +<p>O corpo da classe é a parte que está entre as chavetas <code>{}</code>. É aqui que são definidos os membros da classe, tais como, métodos e construtores.</p> + +<h3 id="Strict_mode_-_modo_estrito">Strict mode - modo estrito</h3> + +<p>Os corpos da <em>declaração de classes </em>e da <em>expressão de classes </em>são executados em <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode">strict mode</a> i.e. construtor, métodos estáticos e de prototipo, funções getter e setter são executadas em modo estrito.</p> + +<h3 id="Construtor_(constructor)">Construtor (<em>constructor</em>)</h3> + +<p>O método <code><a href="/en-US/docs/Web/JavaScript/Reference/Classes/constructor">constructor</a></code> é um método especial para criar e inicializar um objto criado de uma <code>class</code>. 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 <code>constructor</code> será lançada uma {{jsxref("SyntaxError")}}.</p> + +<p>Um construtor pode utlizar a palavra reservada <code>super</code> para invocar o construtor da classe pai.</p> + +<h3 id="Métodos_de_Prototype">Métodos de Prototype </h3> + +<p>Ver também <a href="/en-US/docs/Web/JavaScript/Reference/Functions/Method_definitions">definição de métodos</a>.</p> + +<pre class="brush: js">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</pre> + +<h3 id="Métodos_estáticos">Métodos estáticos</h3> + +<p>A palavra reservada <code><a href="/en-US/docs/Web/JavaScript/Reference/Classes/static">static</a></code> define um método como estático para uma classe. Os métodos estáticos são chamados sem <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript#The_object_(class_instance)" title='An example of class instance is "var john = new Person();"'>instanciarem </a>as suas classes e <strong>não podem </strong>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.</p> + +<pre class="brush: js">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</pre> + +<h3 id="Boxing_com_métodos_estáticos_e_de_protótipo">Boxing com métodos estáticos e de protótipo </h3> + +<p>Quando um método estático é chamado sem um objeto correspondente ao "this", o valor do "this" é então <code>undefined</code> dentro do método chamado. O comportamento será o mesmo, mesmo que a diretiva <code>"use strict"</code> não esteja presente, isto porque o código contido no limite sintático do corpo da <code>class</code> é sempre executado em modo estrito.</p> + +<pre class="brush: js">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</pre> + +<p> </p> + +<p>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 <em>this</em>. Se o valor inicial for <code>undefined</code>, isso será definido para o objeto global.</p> + +<p>Autoboxing não acontecerá no modo estrito, o valor do <em>this </em>permanece como passado ao método.</p> + +<p> </p> + +<pre><code>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</code></pre> + +<h3 id="Propriedades_de_instância">Propriedades de instância</h3> + +<p>Propriedades de instância devem ser definidas dentro de métodos da classe:</p> + +<pre><code>class Rectangle { + constructor(height, width) { + this.height = height; + this.width = width; + } +}</code></pre> + +<p>Propriedades estáticas da classe e propriedades de dados do protótipo devem ser definidas fora da declaração do ClassBody:</p> + +<pre><code>Rectangle.staticWidth = 20; +Rectangle.prototype.prototypeWidth = 25;</code></pre> + +<h3 id="Declaração_de_campos_(Field)">Declaração de campos (<em>Field</em>)</h3> + +<div class="blockIndicator warning"> +<p>Declarações de campo públicos e privados são uma <a href="https://github.com/tc39/proposal-class-fields">funcionalidade experimental (stage 3)</a> proposta no <a href="https://tc39.github.io/beta/">TC39</a>, o comité de padrões JavaScript. O suporte nos navegadores é limitado, mas a funcionalidade pode ser usada por meio de uma etapa de <em>build</em> com sistemas como o <a href="https://babeljs.io/">Babel</a>.</p> +</div> + +<h4 id="Declaração_de_campos_(field_)_públicos">Declaração de campos (<em>field </em>) públicos</h4> + +<p>Com a sintaxe de declaração de campo JavaScript, o exemplo acima pode ser escrito como:</p> + +<pre><code>class Rectangle { + height = 0; + width; + constructor(height, width) { + this.height = height; + this.width = width; + } +}</code></pre> + +<p> </p> + +<p>Ao declarar campos antecipadamente, as definições de classe se tornam mais autodocumentadas e os campos estão sempre presentes.</p> + +<p>Como visto acima, os campos podem ser declarados com ou sem um valor padrão.</p> + +<p> </p> + +<h4 id="Declaração_de_campos_(field)_privados">Declaração de campos (<em>field</em>) privados </h4> + +<p>Usando campos privados, a definição pode ser refinada como abaixo.</p> + +<pre><code>class Rectangle { + #height = 0; + #width; + constructor(height, width) { + this.#height = height; + this.#width = width; + } +}</code></pre> + +<p> </p> + +<p>É 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.</p> + +<div class="blockIndicator note"> +<p>Campos privados só podem ser declarados antecipadamente numa declaração de campo.</p> +</div> + +<p>Os campos privados não podem ser criados posteriormente através da sua afetação, como se pode fazer com as propriedades normais.</p> + +<p> </p> + +<p> </p> + +<p> </p> + +<p> </p> + +<p> </p> + +<p> </p> + +<h2 id="Derivação_de_classes_com_extends">Derivação de classes com <code>extends</code></h2> + +<p>A palavra reservada <code><a href="/en-US/docs/Web/JavaScript/Reference/Classes/extends">extends</a></code> é utilizada na <em>declaração de classes </em>ou na <em>expressão de classes</em> para criar uma classe filha ou derivada de outra .</p> + +<pre class="brush: js">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. +</pre> + +<p>Se houver um construtor presente numa classe derivada, este precisa de chamar super() antes de utilizar o "this".</p> + +<p>A tradicionais "classes" function-based podem também ser extendidas:</p> + +<pre class="brush: js">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. +</pre> + +<p>É 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()")}}:</p> + +<pre class="brush: js">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. +</pre> + +<h2 id="Espécies">Espécies</h2> + +<p>Se quiser devolver um objeto do tipo {{jsxref("Array")}} na sua classe derivada <code>MyArray</code>. O padrão espécies permite-lhe redefinir o construtor por omissão.</p> + +<p>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 <code>Array</code>, em vez de um objeto <code>MyArray</code>. O símbolo {{jsxref("Symbol.species")}} permite fazer isto:</p> + +<pre class="brush: js">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 +</pre> + +<h2 id="Chamadas_à_super_classe_com_super">Chamadas à super classe com <code>super</code></h2> + +<p>A palavra reservada <code><a href="/en-US/docs/Web/JavaScript/Reference/Operators/super">super</a></code> é utilizada para chamar funções no objeto pai do objeto.</p> + +<pre class="brush: js">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. + +</pre> + +<h2 id="Mix-ins">Mix-ins</h2> + +<p>A subclasses abstratas ou <em>mix-ins</em> 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.</p> + +<p>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.:</p> + +<pre class="brush: js">var calculatorMixin = Base => class extends Base { + calc() { } +}; + +var randomizerMixin = Base => class extends Base { + randomize() { } +}; +</pre> + +<p>Uma classe que usa esses mix-ins pode ser escrita assim:</p> + +<pre class="brush: js">class Foo { } +class Bar extends calculatorMixin(randomizerMixin(Foo)) { }</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-class-definitions', 'Class definitions')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Definição inicial.</td> + </tr> + <tr> + <td>{{SpecName('ES2016', '#sec-class-definitions', 'Class definitions')}}</td> + <td>{{Spec2('ES2016')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES2017', '#sec-class-definitions', 'Class definitions')}}</td> + <td>{{Spec2('ES2017')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-class-definitions', 'Class definitions')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_no_Browser">Compatibilidade no Browser </h2> + +<div class="hidden">A tabela de compatibilidade nesta página é gerada a partir de dados estruturados. Se você quiser contribuir com os dados, consulte: <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> e envie-nos um pull request.</div> + +<p>{{Compat("javascript.classes")}}</p> + +<h2 id="Executar_no_Scratchpad">Executar no Scratchpad</h2> + +<p>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>.</p> + +<p>Para voltar a executar uma definição, utilise o menu Scratchpad's Execute > Reload and Run.<br> + Vote, por favor, no bug <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=1428672">#1428672</a>.</p> + +<h2 id="Veja_também">Veja também</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Functions">Functions</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Statements/class"><code>class</code> declaration</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Operators/class"><code>class</code> expression</a></li> + <li>{{jsxref("Operators/super", "super")}}</li> + <li><a href="https://hacks.mozilla.org/2015/07/es6-in-depth-classes/">Blog post: "ES6 In Depth: Classes"</a></li> +</ul> diff --git a/files/pt-pt/web/javascript/reference/classes/static/index.html b/files/pt-pt/web/javascript/reference/classes/static/index.html new file mode 100644 index 0000000000..9cb5c48367 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/classes/static/index.html @@ -0,0 +1,131 @@ +--- +title: static +slug: Web/JavaScript/Reference/Classes/static +translation_of: Web/JavaScript/Reference/Classes/static +--- +<div>{{jsSidebar("Classes")}}</div> + +<p>A palavra-chave <code><strong>static</strong></code> define um método estático para uma classe.</p> + +<div>{{EmbedInteractiveExample("pages/js/classes-static.html")}}</div> + + + +<h2 id="Síntaxe">Síntaxe</h2> + +<pre class="syntaxbox">static <em>nomeDoMetodo</em>() { ... }</pre> + +<h2 id="Descrição">Descrição</h2> + +<p>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.</p> + +<h2 id="Como_chamar_métodos_estáticos">Como chamar métodos estáticos</h2> + +<h3 id="Noutro_método_estático">Noutro método estático</h3> + +<p>Para chamar um método estático dentro de outro que pertença à mesma classe, pode-se usar a palavra-chave <code><a href="/en-US/docs/Web/JavaScript/Reference/Operators/this">this</a></code>.</p> + +<pre class="brush: js">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'</pre> + +<h3 id="No_construtor_de_classe_e_noutros_métodos">No construtor de classe e noutros métodos</h3> + +<p>Métodos estáticos não são acessíveis através da palavra-chave <code><a href="/en-US/docs/Web/JavaScript/Reference/Operators/this">this</a></code> quando dentro de métodos não-estáticos. É preciso chamá-los ou através do nome da própria classe: <code>CLASSNAME.STATIC_METHOD_NAME()</code> ou como propriedade do construtor da classe: <code>this.constructor.STATIC_METHOD_NAME()</code>.</p> + +<pre class="brush: js">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.'; + } +}</pre> + +<h2 id="Exemplos">Exemplos</h2> + +<p>Os seguintes exemplos demonstram:</p> + +<ol> + <li>Como implementar um método estático numa classe.</li> + <li>Que se podem criar sub-classes a partir de uma classe com um membro estático (e usá-los).</li> + <li>Como se pode chamar um método estático (com contra-exemplos).</li> +</ol> + +<pre class="brush: js">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) +</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-class-definitions', 'Definições de Classe')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Definição inicial.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-class-definitions', 'Definições de Classe')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_de_browsers">Compatibilidade de browsers</h2> + + + +<p>{{Compat("javascript.classes.static")}}</p> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Operators/class">expressão <code>class</code></a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Statements/class">declaração <code>class</code></a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Classes">Classes</a></li> +</ul> diff --git a/files/pt-pt/web/javascript/reference/errors/declaração_função_sem_nome/index.html b/files/pt-pt/web/javascript/reference/errors/declaração_função_sem_nome/index.html new file mode 100644 index 0000000000..a747257379 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/errors/declaração_função_sem_nome/index.html @@ -0,0 +1,113 @@ +--- +title: 'Erro de sintaxe: declaração de função precisa de um nome' +slug: Web/JavaScript/Reference/Errors/declaração_função_sem_nome +translation_of: Web/JavaScript/Reference/Errors/Unnamed_function_statement +--- +<div>{{jsSidebar("Errors")}}</div> + +<h2 id="Mensagem">Mensagem</h2> + +<pre class="syntaxbox">Syntax Error: Expected identifier (Edge) +SyntaxError: function statement requires a name [Firefox] +SyntaxError: Unexpected token ( [Chrome] +</pre> + +<h2 id="Tipo_de_erro">Tipo de erro</h2> + +<p>{{jsxref("SyntaxError")}}</p> + +<h2 id="O_que_correu_mal">O que correu mal?</h2> + +<p>Existe uma <a href="/en-US/docs/Web/JavaScript/Reference/Statements/function">declaração de função</a> 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</p> + +<p><span class="tlid-translation translation"><span title="">Existe uma </span></span><a href="/en-US/docs/Web/JavaScript/Reference/Statements/function">declaração de função</a><span class="tlid-translation translation"><span title=""> no código que requer um nome.</span> <span title="">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</span> <span title="">código da função esta colocado corretamente neste contexto.</span></span></p> + +<h2 id="Exemplos">Exemplos</h2> + +<h3 id="Declarações_vs_Expressões">Declarações vs Expressões</h3> + +<p>Uma <em><a href="/en-US/docs/Web/JavaScript/Reference/Statements/function">declaração de função</a></em> precisa de um nome, o código seguinte não funciona:</p> + +<pre class="brush: js example-bad">function () { + return 'Hello world'; +} +// SyntaxError: function statement requires a name +</pre> + +<p>É possível usar uma <a href="/en-US/docs/Web/JavaScript/Reference/Operators/function">expressão de função</a> (atribuição) como alternativa:</p> + +<pre class="brush: js example-good">var greet = function() { + return 'Hello world'; +};</pre> + +<p><span class="tlid-translation translation"><span title="">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.</span> Serão precisos<span title=""> mais alguns parêntises neste caso:</span></span></p> + +<pre class="brush: js example-good">(function () { + +})();</pre> + +<h3 id="Funções_com_nome">Funções com nome</h3> + +<p>Se você está a usar uma função com <a href="/en-US/docs/Web/JavaScript/Reference/Statements/label">identificador</a>, <span class="tlid-translation translation"><span title="">ainda precisará fornecer um nome de função após a palavra-chave da função.</span> O código seguinte<span title=""> não funciona:</span></span></p> + +<pre class="brush: js example-bad">function Greeter() { + german: function () { + return "Moin"; + } +} +// SyntaxError: function statement requires a name +</pre> + +<p>O código seguinte irá funcionar por exemplo:</p> + +<pre class="brush: js example-good">function Greeter() { + german: function g() { + return "Moin"; + } +}</pre> + +<h3 id="Métodos_de_objectos">Métodos de objectos</h3> + +<p><span class="tlid-translation translation"><span title="">Se você pretendia criar um método de um objeto, você precisará criar um objeto.</span> <span title="">A sintaxe a seguir sem um nome após a palavra-chave </span></span><code>function</code><span class="tlid-translation translation"><span title=""> é válida.</span></span></p> + +<pre class="brush: js example-good">var greeter = { + german: function () { + return "Moin"; + } +};</pre> + +<h3 id="Sintaxe_de_Callback">Sintaxe de Callback</h3> + +<p>Além disso, verifique a sintaxe ao usar callbacks. Parêntisis e virgurlas podem facilmente se tornar complicados.</p> + +<pre class="brush: js example-bad">promise.then( + function() { + console.log("success"); + }); + function() { + console.log("error"); +} +// SyntaxError: function statement requires a name +</pre> + +<p>:</p> + +<pre class="brush: json example-good">promise.then( + function() { + console.log("success"); + }, + function() { + console.log("error"); + } +); +</pre> + +<h2 id="Veja_também">Veja também</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Guide/Functions">Functions in the JavaScript Guide</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Statements/function">function statement</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Operators/function">function expression</a></li> + <li><a href="https://en.wikipedia.org/wiki/Immediately-invoked_function_expression">IIFE</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Statements/label">label</a></li> +</ul> diff --git a/files/pt-pt/web/javascript/reference/errors/index.html b/files/pt-pt/web/javascript/reference/errors/index.html new file mode 100644 index 0000000000..c295fccea6 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/errors/index.html @@ -0,0 +1,31 @@ +--- +title: JavaScript error reference +slug: Web/JavaScript/Reference/Errors +tags: + - Debugging + - Error + - Errors + - Exception + - JavaScript + - NeedsTranslation + - TopicStub + - exceptions +translation_of: Web/JavaScript/Reference/Errors +--- +<p>{{jsSidebar("Errors")}}</p> + +<p>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 <code>name</code> and a <code>message</code>.</p> + +<p>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.</p> + +<h2 id="List_of_errors">List of errors</h2> + +<p>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!</p> + +<p>{{ListSubPages("/en-US/docs/Web/JavaScript/Reference/Errors")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/What_went_wrong">What went wrong? Troubleshooting JavaScript</a>: Beginner's introductory tutorial on fixing JavaScript errors.</li> +</ul> 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 new file mode 100644 index 0000000000..e17857e074 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/errors/not_a_function/index.html @@ -0,0 +1,172 @@ +--- +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 +--- +<div>{{jsSidebar("Errors")}}</div> + +<p>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.</p> + +<h2 id="Mensagem">Mensagem</h2> + +<pre class="syntaxbox notranslate">TypeError: Object doesn't support property or method {x} (Edge) +TypeError: "x" is not a function +</pre> + +<h2 id="Tipo_de_erro">Tipo de erro</h2> + +<p>{{jsxref("TypeError")}}</p> + +<h2 id="O_que_deu_errado">O que deu errado?</h2> + +<p>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.</p> + +<p>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 <code>Object</code> não tem função de <code>map</code>, mas o <code>Array</code> tem.</p> + +<p>Há muitas funções que necessitam de uma função como parâmetro (<em>callback</em>). Terá de fornecer uma função para que estes métodos funcionem corretamente:</p> + +<ul> + <li>Quando se trabalha com objetos {{jsxref("Array")}} ou {{jsxref("TypedArray")}}: + <ul> + <li>{{jsxref("Array.prototype.every()")}}, {{jsxref("Array.prototype.some()")}}, {{jsxref("Array.prototype.forEach()")}}, {{jsxref("Array.prototype.map()")}}, {{jsxref("Array.prototype.filter()")}}, {{jsxref("Array.prototype.reduce()")}}, {{jsxref("Array.prototype.reduceRight()")}}, {{jsxref("Array.prototype.find()")}}</li> + </ul> + </li> + <li>Quando se trabalha com objetos {{jsxref("Map")}} e {{jsxref("Set")}}: + <ul> + <li>{{jsxref("Map.prototype.forEach()")}} e {{jsxref("Set.prototype.forEach()")}}</li> + </ul> + </li> +</ul> + +<h2 id="Exemplos">Exemplos</h2> + +<h3 id="Um_erro_no_nome_da_função">Um erro no nome da função</h3> + +<p>Neste caso existe um erro no nome função:</p> + +<pre class="brush: js example-bad notranslate">let x = document.getElementByID('foo'); +// TypeError: document.getElementByID is not a function +</pre> + +<p>O nome correto da função é <code>getElementByI<strong>d</strong></code>:</p> + +<pre class="brush: js example-good notranslate">let x = document.getElementById('foo'); +</pre> + +<h3 id="Função_é_chamada_no_objeto_errado">Função é chamada no objeto errado</h3> + +<p>Para certos métodos, é necessário fornecer uma função (<em>callback</em>) e funcionará apenas em objetos específicos. Neste exemplo, é utilizado o {{jsxref("Array.prototype.map()")}}, que funcionará apenas com objetos {{jsxref("Array")}}.</p> + +<pre class="brush: js example-bad notranslate">let obj = {a: 13, b: 37, c: 42}; + +obj.map(function(num) { + return num * 2; +}); + +// TypeError: obj.map is not a function</pre> + +<p>Use antes uma matriz:</p> + +<pre class="brush: js example-good notranslate">let numbers = [1, 4, 9]; + +numbers.map(function(num) { + return num * 2; +}); + +// Array [2, 8, 18] +</pre> + +<h3 id="Function_shares_a_name_with_a_pre-existing_property">Function shares a name with a pre-existing property</h3> + +<p>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.</p> + +<pre class="brush: js example-bad notranslate">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 +</pre> + +<p>Use um nome diferente para a propriedade:</p> + +<pre class="brush: js example-good notranslate">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' } +</pre> + +<h3 id="Usar_parênteses_para_multiplicação">Usar parênteses para multiplicação</h3> + +<p>Em matemática, pode escrever 2 × (3 + 5) como 2*(3 + 5) ou somente 2(3 + 5).</p> + +<p>Usar a última forma dá um erro:</p> + +<pre class="js example-bad notranslate">const sixteen = 2(3 + 5); +alert('2 x (3 + 5) is ' + String(sixteen)); +//Uncaught TypeError: 2 is not a function</pre> + +<p>Pode corrigir o erro com a operadora <code>*</code>:</p> + +<pre class="js example-good notranslate">const sixteen = 2 * (3 + 5); +alert('2 x (3 + 5) is ' + String(sixteen)); +//2 x (3 + 5) is 16 +</pre> + +<h3 id="Importar_o_modulo_exportado_corretamente">Importar o modulo exportado corretamente</h3> + +<p>Certifique-se que está a importar o módulo corretamente.</p> + +<p>Um exemplo de uma biblioteca <em>helper</em> (<code>helpers.js</code>)</p> + +<pre class="brush: js notranslate">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; +</pre> + +<p>A utilização correta de importação (para <code>App.js</code>) é:</p> + +<pre class="notranslate">import helpers from './helpers'</pre> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li><a href="/pt-PT/docs/Web/JavaScript/Reference/Funcoes">Funções</a></li> +</ul> 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 new file mode 100644 index 0000000000..f3d1de92c8 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/errors/stmt_after_return/index.html @@ -0,0 +1,77 @@ +--- +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 +--- +<div>{{jsSidebar("Errors")}}</div> + +<h2 id="Mensagem">Mensagem</h2> + +<pre class="syntaxbox">Warning: unreachable code after return statement (Firefox) +</pre> + +<h2 id="Tipo_de_ErroEdit">Tipo de Erro<a class="button section-edit only-icon" href="https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Errors/Stmt_after_return$edit#Tipo_de_Erro" rel="nofollow, noindex"><span>Edit</span></a></h2> + +<p>Aviso</p> + +<h2 id="O_que_correu_malEdit">O que correu mal?<a class="button section-edit only-icon" href="https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Errors/Stmt_after_return$edit#O_que_deu_errado" rel="nofollow, noindex"><span>Edit</span></a></h2> + +<p><em>Unreachable code after return statement</em> pode ocorrer nas seguintes situações:</p> + +<ul> + <li>Quando é utilizada uma expressão depois de uma declaração <a href="/pt-PT/docs/Web/JavaScript/Reference/Extratos_e_declarações/return" title="A declaração return finaliza a execução de uma função e especifica os valores que devem ser retonados para onde a função foi chamada."><code>return</code></a> , ou</li> + <li>quando é utilizada uma declaração <em>return</em> sem ponto e vírgula, mas incluindo uma declaração diretamente depois.</li> +</ul> + +<p>Quando existe uma expressão depois de uma declaração <code>return</code> válida, é dado um aviso para indicar que o código depois da declaração <code>return</code> é inacessível, o que significa que o mesmo nunca pode ser executado.</p> + +<p>Porquê é que eu deveria ter ponto e vírgula depois de declarações <code>return</code>? No caso de declarações <code>return</code> 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 <code>return</code> foi escrita.</p> + +<p>Os avisos não serão apresentados para declarações <em>return</em> sem ponto-e-vírgula nas seguintes situações:</p> + +<ul> + <li>{{jsxref("Statements/throw", "throw")}}</li> + <li>{{jsxref("Statements/break", "break")}}</li> + <li>{{jsxref("Statements/var", "var")}}</li> + <li>{{jsxref("Statements/function", "function")}}</li> +</ul> + +<h2 id="Exemplos">Exemplos</h2> + +<h3 id="Casos_inválidos">Casos inválidos</h3> + +<pre class="brush: js example-bad">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 +} +</pre> + +<h3 id="Casos_válidos">Casos válidos</h3> + +<pre class="brush: js example-good">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 +} +</pre> + +<h2 id="Consulte_tambémEdit">Consulte também<a class="button section-edit only-icon" href="https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Errors/Stmt_after_return$edit#Ver_também" rel="nofollow, noindex"><span>Edit</span></a></h2> + +<ul> + <li>{{jsxref("Statements/return", "Automatic Semicolon Insertion", "#Automatic_Semicolon_Insertion", 1)}}</li> +</ul> 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 new file mode 100644 index 0000000000..55103f82a7 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/errors/unexpected_token/index.html @@ -0,0 +1,50 @@ +--- +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 +--- +<div>{{jsSidebar("Errors")}}</div> + +<h2 id="Mensagem">Mensagem</h2> + +<pre class="syntaxbox">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" +</pre> + +<h2 id="Tipo_de_erro">Tipo de erro</h2> + +<p>{{jsxref("SyntaxError")}}</p> + +<h2 id="O_que_aconteceu_de_errado">O que aconteceu de errado?</h2> + +<p>É esperado um contrutor de linguagem específico, mas foi entregue outra coisa qualquer. Isto poderá ser simplesmente um erro de escrita.</p> + +<h2 id="Exemplos">Exemplos</h2> + +<h3 id="Expressão_esperada">Expressão esperada</h3> + +<p>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.</p> + +<pre class="brush: js example-bad">Math.max(2, 42,); +// SyntaxError: expected expression, got ')' +</pre> + +<p>Para corrigir o problema, retirava-se a virgula ou adicionavam-se mais argumentos:</p> + +<pre class="brush: js example-good">Math.max(2, 42); +Math.max(2, 42, 13 + 37); +</pre> + +<h2 id="Veja_também">Veja também</h2> + +<ul> + <li>{{jsxref("Math.max()")}}</li> +</ul> diff --git a/files/pt-pt/web/javascript/reference/extratos_e_declarações/bloco/index.html b/files/pt-pt/web/javascript/reference/extratos_e_declarações/bloco/index.html new file mode 100644 index 0000000000..a3104dbeae --- /dev/null +++ b/files/pt-pt/web/javascript/reference/extratos_e_declarações/bloco/index.html @@ -0,0 +1,116 @@ +--- +title: Bloco (block) +slug: Web/JavaScript/Reference/Extratos_e_declarações/bloco +tags: + - Declaração + - Funcionalidade de Linguagem + - JavaScript + - Referencia +translation_of: Web/JavaScript/Reference/Statements/block +--- +<div>Bloco {{jsSidebar("Statements")}}</div> + +<p>Uma <strong>declaralção bloco </strong>(ou <strong>declaração composto</strong> 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)}}:</p> + +<div>{{EmbedInteractiveExample("pages/js/statement-block.html", "taller")}}</div> + + + +<h2 id="Sintaxe">Sintaxe</h2> + +<h3 id="Declaração_de_Bloco">Declaração de Bloco</h3> + +<pre class="syntaxbox">{ + <em>StatementList</em> +} +</pre> + +<h3 id="Declaração_de_Bloco_Etiquetado">Declaração de Bloco Etiquetado</h3> + +<pre class="syntaxbox"><em>LabelIdentifier</em>: { + <em>StatementList</em> +} +</pre> + +<dl> + <dt><code>StatementList</code></dt> + <dd>Statements grouped within the block statement.</dd> + <dt><code>LabelIdentifier</code></dt> + <dd>An optional {{jsxref("Statements/label", "label", "", 1)}} for visual identification or as a target for {{jsxref("Statements/break", "break")}}.</dd> +</dl> + +<h2 id="Descrição">Descrição</h2> + +<p>The block statement is often called <strong>compound statement</strong> 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 <a href="/en-US/docs/Web/JavaScript/Reference/Statements/Empty">empty statement</a>, where you provide no statement, although one is required.</p> + +<p>Blocks are commonly used in association with {{jsxref("Statements/if...else", "if...else")}} and {{jsxref("Statements/for", "for")}} statements.</p> + +<h3 id="Block_Scoping_Rules">Block Scoping Rules</h3> + +<h4 id="With_var_or_function_declaration_in_non-strict_mode">With <code>var</code> or function declaration in non-strict mode</h4> + +<p>Variables declared with <code>var</code> or created by <a href="/en-US/docs/Web/JavaScript/Reference/Statements/function">function declarations</a> in non-strict mode <strong>do not</strong> 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:</p> + +<pre class="brush: js example-bad">var x = 1; +{ + var x = 2; +} +console.log(x); // logs 2 +</pre> + +<p>This logs 2 because the <code>var x</code> statement within the block is in the same scope as the <code>var x</code> statement before the block.</p> + +<p>In non-strict code, function declarations inside blocks behave strangely. Do not use them.</p> + +<h4 id="With_let_const_or_function_declaration_in_strict_mode">With <code>let</code>, <code>const</code> or function declaration in strict mode</h4> + +<p>By contrast, identifiers declared with {{jsxref("Statements/let", "let")}} and {{jsxref("Statements/const", "const")}} <strong>do have </strong>block scope:</p> + +<pre class="brush: js">let x = 1; +{ + let x = 2; +} +console.log(x); // logs 1</pre> + +<p>The <code>x = 2</code> is limited in scope to the block in which it was defined.</p> + +<p>The same is true of <code>const</code>:</p> + +<pre class="brush: js">const c = 1; +{ + const c = 2; +} +console.log(c); // logs 1 and does not throw SyntaxError...</pre> + +<p>Note that the block-scoped <code>const c = 2</code> <em>does not</em> throw a <code>SyntaxError: Identifier 'c' has already been declared</code> because it can be declared uniquely within the block.</p> + +<p>In <a href="/en-US/docs/Web/JavaScript/Reference/Strict_mode">strict mode</a>, starting with ES2015, functions inside blocks are scoped to that block. Prior to ES2015, block-level functions were forbidden in strict mode.</p> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificação</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('ESDraft', '#sec-block', 'Block statement')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_de_navegador">Compatibilidade de navegador</h2> + + + +<p>{{Compat("javascript.statements.block")}}</p> + +<h2 id="Consulte_também">Consulte também</h2> + +<ul> + <li>{{jsxref("Statements/while", "while")}}</li> + <li>{{jsxref("Statements/if...else", "if...else")}}</li> + <li>{{jsxref("Statements/let", "let")}}</li> +</ul> diff --git a/files/pt-pt/web/javascript/reference/extratos_e_declarações/for/index.html b/files/pt-pt/web/javascript/reference/extratos_e_declarações/for/index.html new file mode 100644 index 0000000000..ac7586e98b --- /dev/null +++ b/files/pt-pt/web/javascript/reference/extratos_e_declarações/for/index.html @@ -0,0 +1,145 @@ +--- +title: for +slug: Web/JavaScript/Reference/Extratos_e_declarações/for +tags: + - Declaração + - Funcionalidade de Linguagem + - JavaScript + - Loop + - Referencia + - Repetição + - for +translation_of: Web/JavaScript/Reference/Statements/for +--- +<div>{{jsSidebar("Statements")}}</div> + +<p>A <strong>declaração "for"</strong> cria uma repetição (<em>loop</em>) que consiste de três expressões opcionais, entre parênteses e separados por ponto e vírgula, seguido de uma declaração (normalmente <a href="/pt-PT/docs/Web/JavaScript/Reference/Extratos_e_declarações/bloco">bdeclaraçãod e bloco (<em>block</em>)</a>) para ser executada na repetição.</p> + +<div>{{EmbedInteractiveExample("pages/js/statement-for.html")}}</div> + + + +<h2 id="Sintaxe">Sintaxe</h2> + +<pre class="syntaxbox">for ([<em>initialization</em>]; [<em>condition</em>]; [<em>final-expression</em>]) + <em>statement</em></pre> + +<dl> + <dt><code>initialization</code></dt> + <dd>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 <code>var</code> or <code>let</code> keywords. Variables declared with <code>var</code> are not local to the loop, i.e. they are in the same scope the <code>for</code> loop is in. Variables declared with let are local to the statement.</dd> + <dd>The result of this expression is discarded.</dd> + <dt><code>condition</code></dt> + <dd>An expression to be evaluated before each loop iteration. If this expression evaluates to true, <code>statement</code> 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 <code>for</code> construct.</dd> + <dt><code>final-expression</code></dt> + <dd>An expression to be evaluated at the end of each loop iteration. This occurs before the next evaluation of <code>condition</code>. Generally used to update or increment the counter variable.</dd> + <dt><code>statement</code></dt> + <dd>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 (<code>{ ... }</code>) to group those statements. To execute no statement within the loop, use an {{jsxref("Statements/empty", "empty", "", 0)}} statement (<code>;</code>).</dd> +</dl> + +<h2 id="Exemplos">Exemplos</h2> + +<h3 id="Using_for">Using <code>for</code></h3> + +<p>The following <code>for</code> statement starts by declaring the variable <code>i</code> and initializing it to <code>0</code>. It checks that <code>i</code> is less than nine, performs the two succeeding statements, and increments <code>i</code> by 1 after each pass through the loop.</p> + +<pre class="brush: js">for (let i = 0; i < 9; i++) { + console.log(i); + // more statements +} +</pre> + +<h3 id="Optional_for_expressions">Optional <code>for</code> expressions</h3> + +<p>All three expressions in the head of the <code>for</code> loop are optional.</p> + +<p>For example, in the <em>initialization</em> block it is not required to initialize variables:</p> + +<pre class="brush: js">var i = 0; +for (; i < 9; i++) { + console.log(i); + // more statements +} +</pre> + +<p>Like the <em>initialization</em> block, the <em>condition</em> 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.</p> + +<pre class="brush: js">for (let i = 0;; i++) { + console.log(i); + if (i > 3) break; + // more statements +}</pre> + +<p>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.</p> + +<pre class="brush: js">var i = 0; + +for (;;) { + if (i > 3) break; + console.log(i); + i++; +} +</pre> + +<h3 id="Using_for_without_a_statement">Using <code>for</code> without a statement</h3> + +<p>The following <code>for</code> cycle calculates the offset position of a node in the <em>final-expression</em> section, and therefore it does not require the use of a <code>statement</code> section, a semicolon is used instead.</p> + +<pre class="brush: js">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;"</pre> + +<div class="note"><strong>Note:</strong> This is one of the few cases in JavaScript where <strong>the semicolon is mandatory</strong>. Indeed, without the semicolon the line that follows the cycle declaration will be considered a statement.</div> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificação</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-for-statement', 'for statement')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_de_navegador">Compatibilidade de navegador</h2> + + + +<p>{{Compat("javascript.statements.for")}}</p> + +<h2 id="Consulte_também">Consulte também</h2> + +<ul> + <li>{{jsxref("Statements/empty", "empty statement", "", 0)}}</li> + <li>{{jsxref("Statements/break", "break")}}</li> + <li>{{jsxref("Statements/continue", "continue")}}</li> + <li>{{jsxref("Statements/while", "while")}}</li> + <li>{{jsxref("Statements/do...while", "do...while")}}</li> + <li>{{jsxref("Statements/for...in", "for...in")}}</li> + <li>{{jsxref("Statements/for...of", "for...of")}}</li> +</ul> diff --git a/files/pt-pt/web/javascript/reference/extratos_e_declarações/index.html b/files/pt-pt/web/javascript/reference/extratos_e_declarações/index.html new file mode 100644 index 0000000000..af841906a1 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/extratos_e_declarações/index.html @@ -0,0 +1,150 @@ +--- +title: Declarações e instruções +slug: Web/JavaScript/Reference/Extratos_e_declarações +tags: + - JavaScript + - Referencia + - declarações + - instruções +translation_of: Web/JavaScript/Reference/Statements +--- +<div>{{jsSidebar("Statements")}}</div> + +<p>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.</p> + +<h2 id="Declarações_e_instruções_por_categoria">Declarações e instruções por categoria</h2> + +<p>For an alphabetical listing see the sidebar on the left.</p> + +<h3 id="Controlo_de_Fluxo">Controlo de Fluxo</h3> + +<dl> + <dt>{{jsxref("Statements/block", "Block")}}</dt> + <dd>A block statement is used to group zero or more statements. The block is delimited by a pair of curly brackets.</dd> + <dt>{{jsxref("Statements/break", "break")}}</dt> + <dd>Terminates the current loop, switch, or label statement and transfers program control to the statement following the terminated statement.</dd> + <dt>{{jsxref("Statements/continue", "continue")}}</dt> + <dd>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.</dd> + <dt>{{jsxref("Statements/Empty", "Empty")}}</dt> + <dd>An empty statement is used to provide no statement, although the JavaScript syntax would expect one.</dd> + <dt>{{jsxref("Statements/if...else", "if...else")}}</dt> + <dd>Executes a statement if a specified condition is true. If the condition is false, another statement can be executed.</dd> + <dt>{{jsxref("Statements/switch", "switch")}}</dt> + <dd>Evaluates an expression, matching the expression's value to a case clause, and executes statements associated with that case.</dd> + <dt>{{jsxref("Statements/throw", "throw")}}</dt> + <dd>Throws a user-defined exception.</dd> + <dt>{{jsxref("Statements/try...catch", "try...catch")}}</dt> + <dd>Marks a block of statements to try, and specifies a response, should an exception be thrown.</dd> +</dl> + +<h3 id="Declarações">Declarações</h3> + +<dl> + <dt>{{jsxref("Statements/var", "var")}}</dt> + <dd>Declares a variable, optionally initializing it to a value.</dd> + <dt>{{jsxref("Statements/let", "let")}}</dt> + <dd>Declares a block scope local variable, optionally initializing it to a value.</dd> + <dt>{{jsxref("Statements/const", "const")}}</dt> + <dd>Declares a read-only named constant.</dd> +</dl> + +<h3 id="Funções_e_classes">Funções e classes</h3> + +<dl> + <dt>{{jsxref("Statements/function", "function")}}</dt> + <dd>Declara as funções com parâmetros especificados.</dd> + <dt>{{jsxref("Statements/function*", "function*")}}</dt> + <dd>Generators functions enable writing <a href="/en-US/docs/Web/JavaScript/Guide/The_Iterator_protocol">iterators</a> more easily.</dd> + <dt>{{jsxref("Statements/async_function", "async function")}}</dt> + <dd>Declares an async function with the specified parameters.</dd> + <dt>{{jsxref("Statements/return", "return")}}</dt> + <dd>Specifies the value to be returned by a function.</dd> + <dt>{{jsxref("Statements/class", "class")}}</dt> + <dd>Declara uma Classe.</dd> +</dl> + +<h3 id="Iterações">Iterações</h3> + +<dl> + <dt>{{jsxref("Statements/do...while", "do...while")}}</dt> + <dd>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.</dd> + <dt>{{jsxref("Statements/for", "for")}}</dt> + <dd>Creates a loop that consists of three optional expressions, enclosed in parentheses and separated by semicolons, followed by a statement executed in the loop.</dd> + <dt>{{deprecated_inline}} {{non-standard_inline()}} {{jsxref("Statements/for_each...in", "for each...in")}}</dt> + <dd>Iterates a specified variable over all values of object's properties. For each distinct property, a specified statement is executed.</dd> + <dt>{{jsxref("Statements/for...in", "for...in")}}</dt> + <dd>Iterates over the enumerable properties of an object, in arbitrary order. For each distinct property, statements can be executed.</dd> + <dt>{{jsxref("Statements/for...of", "for...of")}}</dt> + <dd>Iterates over iterable objects (including {{jsxref("Global_Objects/Array","arrays","","true")}}, array-like objects, <a href="/en-US/docs/JavaScript/Guide/Iterators_and_Generators">iterators and generators</a>), invoking a custom iteration hook with statements to be executed for the value of each distinct property.</dd> + <dt>{{jsxref("Statements/while", "while")}}</dt> + <dd>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.</dd> +</dl> + +<h3 id="Outros">Outros</h3> + +<dl> + <dt>{{jsxref("Statements/debugger", "debugger")}}</dt> + <dd>Invokes any available debugging functionality. If no debugging functionality is available, this statement has no effect.</dd> + <dt>{{jsxref("Statements/export", "export")}}</dt> + <dd>Used to export functions to make them available for imports in external modules, another scripts.</dd> + <dt>{{jsxref("Statements/import", "import")}}</dt> + <dd>Used to import functions exported from an external module, another script.</dd> + <dt><code><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import.meta">import.meta</a></code></dt> + <dd>A meta-property exposing context-specific metadata to a JavaScript module.</dd> + <dt>{{jsxref("Statements/label", "label")}}</dt> + <dd>Provides a statement with an identifier that you can refer to using a <code>break</code> or <code>continue</code> statement.</dd> +</dl> + +<dl> + <dt>{{deprecated_inline}} {{jsxref("Statements/with", "with")}}</dt> + <dd>Extends the scope chain for a statement.</dd> +</dl> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + <tr> + <td>{{SpecName('ES1', '#sec-12', 'Statements')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition</td> + </tr> + <tr> + <td>{{SpecName('ES3', '#sec-12', 'Statements')}}</td> + <td>{{Spec2('ES3')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-12', 'Statements')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-ecmascript-language-statements-and-declarations', 'ECMAScript Language: Statements and Declarations')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>New: function*, let, for...of, yield, class</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-ecmascript-language-statements-and-declarations', 'ECMAScript Language: Statements and Declarations')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_de_navegador">Compatibilidade de navegador</h2> + + + +<p>{{Compat("javascript.statements")}}</p> + +<h2 id="Consultar_também">Consultar também</h2> + +<ul> + <li><a href="/pt-PT/docs/Web/JavaScript/Reference/Operadores">Operadores</a></li> +</ul> diff --git a/files/pt-pt/web/javascript/reference/extratos_e_declarações/return/index.html b/files/pt-pt/web/javascript/reference/extratos_e_declarações/return/index.html new file mode 100644 index 0000000000..6cec134992 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/extratos_e_declarações/return/index.html @@ -0,0 +1,148 @@ +--- +title: return +slug: Web/JavaScript/Reference/Extratos_e_declarações/return +tags: + - Declaração + - JavaScript +translation_of: Web/JavaScript/Reference/Statements/return +--- +<div>{{jsSidebar("Statements")}}</div> + +<p>The <strong><code>return</code> statement</strong> ends function execution and specifies a value to be returned to the function caller.</p> + +<h2 id="Sintaxe">Sintaxe</h2> + +<pre class="syntaxbox">return [[expression]]; </pre> + +<dl> + <dt><code>expression</code></dt> + <dd>The expression whose value is to be returned. If omitted, <code>undefined</code> is returned instead.</dd> +</dl> + +<h2 id="Descrição">Descrição</h2> + +<p>When a <code>return</code> 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, <code>x</code>, where <code>x</code> is a number.</p> + +<pre class="brush: js">function square(x) { + return x * x; +} +var demo = square(3); +// demo will equal 9 +</pre> + +<p>If the value is omitted, <code>undefined</code> is returned instead.</p> + +<p>The following return statements all break the function execution:</p> + +<pre class="brush: js">return; +return true; +return false; +return x; +return x + y / 3; +</pre> + +<h3 id="Inserção_Automática_de_Ponto_e_Vírgula">Inserção Automática de Ponto e Vírgula</h3> + +<p>The <code>return</code> statement is affected by <a href="/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Automatic_semicolon_insertion">automatic semicolon insertion (ASI)</a>. No line terminator is allowed between the <code>return</code> keyword and the expression.</p> + +<pre class="brush: js">return +a + b; +</pre> + +<p>is transformed by ASI into:</p> + +<pre>return; +a + b; +</pre> + +<p>The console will warn "unreachable code after return statement".</p> + +<div class="note">Starting with Gecko 40 {{geckoRelease(40)}}, a warning is shown in the console if unreachable code is found after a return statement.</div> + +<h2 id="Exemplos">Exemplos</h2> + +<h3 id="Interromper_uma_função">Interromper uma função</h3> + +<p>A function immediately stops at the point where <code>return</code> is called.</p> + +<pre class="brush: js">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 +</pre> + +<h3 id="Devolver_uma_função">Devolver uma função</h3> + +<p>See also the article about <a href="/en-US/docs/Web/JavaScript/Closures">Closures</a>.</p> + +<pre class="brush: js">function magic(x) { + return function calc(x) { return x * 42; }; +} + +var answer = magic(); +answer(1337); // 56154 +</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-12.9', 'Return statement')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-return-statement', 'Return statement')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-return-statement', 'Return statement')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_de_navegador">Compatibilidade de navegador</h2> + + + +<p>{{Compat("javascript.statements.return")}}</p> + +<h2 id="Consulte_também">Consulte também</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope" title="En/Core_JavaScript_1.5_Reference/Functions">Functions</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Closures">Closures</a></li> +</ul> diff --git a/files/pt-pt/web/javascript/reference/extratos_e_declarações/throw/index.html b/files/pt-pt/web/javascript/reference/extratos_e_declarações/throw/index.html new file mode 100644 index 0000000000..9e7a8bf54e --- /dev/null +++ b/files/pt-pt/web/javascript/reference/extratos_e_declarações/throw/index.html @@ -0,0 +1,271 @@ +--- +title: throw +slug: Web/JavaScript/Reference/Extratos_e_declarações/throw +tags: + - Comando + - Declaração + - JavaScript +translation_of: Web/JavaScript/Reference/Statements/throw +--- +<div>{{jsSidebar("Statements")}}</div> + +<p>A <strong>declaração <code>throw</code> </strong>lança uma exeção definida pelo utilizador. A execução da função atual irá parar (os comandos depois de <code>throw</code> não serão executados), <span id="result_box" lang="pt"><span>e o controle será passado para o primeiro bloco <code><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch">catch</a></code> no conjunto de chamadas. Se não existir nenhum bloco <code>catch</code> entre as funções de <em>caller</em>, o programa irá terminar.</span></span></p> + +<h2 id="Sintaxe">Sintaxe</h2> + +<pre class="syntaxbox">expressão throw; </pre> + +<dl> + <dt><code>expressão</code></dt> + <dd>A expressão para <em>throw</em>.</dd> +</dl> + +<h2 id="Descrição">Descrição</h2> + +<p>Use the <code>throw</code> statement to throw an exception. When you throw an exception, <code>expression</code> specifies the value of the exception. Each of the following throws an exception:</p> + +<pre class="brush: js">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</pre> + +<p>Also note that the <code>throw</code> statement is affected by <a href="/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Automatic_semicolon_insertion">automatic semicolon insertion (ASI)</a> as no line terminator between the <code>throw</code> keyword and the expression is allowed.</p> + +<h2 id="Exemplos">Exemplos</h2> + +<h3 id="Throw_um_objeto">Throw um objeto</h3> + +<p>You can specify an object when you throw an exception. You can then reference the object's properties in the <code>catch</code> block. The following example creates an object of type <code>UserException</code> and uses it in a <code>throw</code> statement.</p> + +<pre class="brush: js">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 +} +</pre> + +<h3 id="Outro_exemplo_de_throwing_um_objeto">Outro exemplo de <em>throwing</em> um objeto</h3> + +<p>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 <code>ZipCodeFormatException</code>.</p> + +<pre class="brush: js">/* + * 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 +</pre> + +<h3 id="Rethrow_uma_exceção"><em>Rethrow</em> uma exceção</h3> + +<p>You can use <code>throw</code> 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.</p> + +<pre class="brush: js">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; + } +} +</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + <tr> + <td>{{SpecName('ES3')}}</td> + <td>{{Spec2('ES3')}}</td> + <td>Initial definition. Implemented in JavaScript 1.4</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-12.13', 'throw statement')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-throw-statement', 'throw statement')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-throw-statement', 'throw statement')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_de_navegador">Compatibilidade de navegador</h2> + + + +<p>{{Compat("javascript.statements.throw")}}</p> + +<h2 id="Consulte_também">Consulte também</h2> + +<ul> + <li><a href="/pt-PT/docs/Web/JavaScript/Reference/Extratos_e_declarações/try...catch"><code>try...catch</code></a></li> +</ul> + +<div id="SL_balloon_obj" style="display: block;"> +<div class="SL_ImTranslatorLogo" id="SL_button" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%; opacity: 0; display: block; left: -8px; top: -25px; transition: visibility 2s ease 0s, opacity 2s linear 0s;"> </div> + +<div id="SL_shadow_translation_result2" style="display: none;"> </div> + +<div id="SL_shadow_translator" style="display: none;"> +<div id="SL_planshet"> +<div id="SL_arrow_up" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<div id="SL_Bproviders"> +<div class="SL_BL_LABLE_ON" id="SL_P0" title="Google">G</div> + +<div class="SL_BL_LABLE_ON" id="SL_P1" title="Microsoft">M</div> + +<div class="SL_BL_LABLE_ON" id="SL_P2" title="Translator">T</div> +</div> + +<div id="SL_alert_bbl" style="display: none;"> +<div id="SLHKclose" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<div id="SL_alert_cont"> </div> +</div> + +<div id="SL_TB"> +<table id="SL_tables"> + <tbody><tr> + <td class="SL_td"><input></td> + <td class="SL_td"><select><option value="auto">Detectar idioma</option><option value="af">Africâner</option><option value="sq">Albanês</option><option value="de">Alemão</option><option value="ar">Arabe</option><option value="hy">Armênio</option><option value="az">Azerbaijano</option><option value="eu">Basco</option><option value="bn">Bengali</option><option value="be">Bielo-russo</option><option value="my">Birmanês</option><option value="bs">Bósnio</option><option value="bg">Búlgaro</option><option value="ca">Catalão</option><option value="kk">Cazaque</option><option value="ceb">Cebuano</option><option value="ny">Chichewa</option><option value="zh-CN">Chinês (Simp)</option><option value="zh-TW">Chinês (Trad)</option><option value="si">Cingalês</option><option value="ko">Coreano</option><option value="ht">Crioulo haitiano</option><option value="hr">Croata</option><option value="da">Dinamarquês</option><option value="sk">Eslovaco</option><option value="sl">Esloveno</option><option value="es">Espanhol</option><option value="eo">Esperanto</option><option value="et">Estoniano</option><option value="fi">Finlandês</option><option value="fr">Francês</option><option value="gl">Galego</option><option value="cy">Galês</option><option value="ka">Georgiano</option><option value="el">Grego</option><option value="gu">Gujarati</option><option value="ha">Hauça</option><option value="iw">Hebraico</option><option value="hi">Hindi</option><option value="hmn">Hmong</option><option value="nl">Holandês</option><option value="hu">Húngaro</option><option value="ig">Igbo</option><option value="id">Indonésio</option><option value="en">Inglês</option><option value="yo">Ioruba</option><option value="ga">Irlandês</option><option value="is">Islandês</option><option value="it">Italiano</option><option value="ja">Japonês</option><option value="jw">Javanês</option><option value="kn">Kannada</option><option value="km">Khmer</option><option value="lo">Laosiano</option><option value="la">Latim</option><option value="lv">Letão</option><option value="lt">Lituano</option><option value="mk">Macedônico</option><option value="ml">Malaiala</option><option value="ms">Malaio</option><option value="mg">Malgaxe</option><option value="mt">Maltês</option><option value="mi">Maori</option><option value="mr">Marathi</option><option value="mn">Mongol</option><option value="ne">Nepalês</option><option value="no">Norueguês</option><option value="fa">Persa</option><option value="pl">Polonês</option><option value="pt">Português</option><option value="pa">Punjabi</option><option value="ro">Romeno</option><option value="ru">Russo</option><option value="sr">Sérvio</option><option value="st">Sesotho</option><option value="so">Somália</option><option value="sw">Suaíli</option><option value="su">Sudanês</option><option value="sv">Sueco</option><option value="tg">Tadjique</option><option value="tl">Tagalo</option><option value="th">Tailandês</option><option value="ta">Tâmil</option><option value="cs">Tcheco</option><option value="te">Telugo</option><option value="tr">Turco</option><option value="uk">Ucraniano</option><option value="ur">Urdu</option><option value="uz">Uzbeque</option><option value="vi">Vietnamita</option><option value="yi">Yiddish</option><option value="zu">Zulu</option></select></td> + <td class="SL_td"> + <div id="SL_switch_b" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Alternar Idiomas"> </div> + </td> + <td class="SL_td"><select><option value="af">Africâner</option><option value="sq">Albanês</option><option value="de">Alemão</option><option value="ar">Arabe</option><option value="hy">Armênio</option><option value="az">Azerbaijano</option><option value="eu">Basco</option><option value="bn">Bengali</option><option value="be">Bielo-russo</option><option value="my">Birmanês</option><option value="bs">Bósnio</option><option value="bg">Búlgaro</option><option value="ca">Catalão</option><option value="kk">Cazaque</option><option value="ceb">Cebuano</option><option value="ny">Chichewa</option><option value="zh-CN">Chinês (Simp)</option><option value="zh-TW">Chinês (Trad)</option><option value="si">Cingalês</option><option value="ko">Coreano</option><option value="ht">Crioulo haitiano</option><option value="hr">Croata</option><option value="da">Dinamarquês</option><option value="sk">Eslovaco</option><option value="sl">Esloveno</option><option value="es">Espanhol</option><option value="eo">Esperanto</option><option value="et">Estoniano</option><option value="fi">Finlandês</option><option value="fr">Francês</option><option value="gl">Galego</option><option value="cy">Galês</option><option value="ka">Georgiano</option><option value="el">Grego</option><option value="gu">Gujarati</option><option value="ha">Hauça</option><option value="iw">Hebraico</option><option value="hi">Hindi</option><option value="hmn">Hmong</option><option value="nl">Holandês</option><option value="hu">Húngaro</option><option value="ig">Igbo</option><option value="id">Indonésio</option><option selected value="en">Inglês</option><option value="yo">Ioruba</option><option value="ga">Irlandês</option><option value="is">Islandês</option><option value="it">Italiano</option><option value="ja">Japonês</option><option value="jw">Javanês</option><option value="kn">Kannada</option><option value="km">Khmer</option><option value="lo">Laosiano</option><option value="la">Latim</option><option value="lv">Letão</option><option value="lt">Lituano</option><option value="mk">Macedônico</option><option value="ml">Malaiala</option><option value="ms">Malaio</option><option value="mg">Malgaxe</option><option value="mt">Maltês</option><option value="mi">Maori</option><option value="mr">Marathi</option><option value="mn">Mongol</option><option value="ne">Nepalês</option><option value="no">Norueguês</option><option value="fa">Persa</option><option value="pl">Polonês</option><option value="pt">Português</option><option value="pa">Punjabi</option><option value="ro">Romeno</option><option value="ru">Russo</option><option value="sr">Sérvio</option><option value="st">Sesotho</option><option value="so">Somália</option><option value="sw">Suaíli</option><option value="su">Sudanês</option><option value="sv">Sueco</option><option value="tg">Tadjique</option><option value="tl">Tagalo</option><option value="th">Tailandês</option><option value="ta">Tâmil</option><option value="cs">Tcheco</option><option value="te">Telugo</option><option value="tr">Turco</option><option value="uk">Ucraniano</option><option value="ur">Urdu</option><option value="uz">Uzbeque</option><option value="vi">Vietnamita</option><option value="yi">Yiddish</option><option value="zu">Zulu</option></select></td> + <td class="SL_td"> + <div id="SL_TTS_voice" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Ouça"> </div> + </td> + <td class="SL_td"> + <div class="SL_copy" id="SL_copy" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Copiar"> </div> + </td> + <td class="SL_td"> + <div id="SL_bbl_font_patch"> </div> + + <div class="SL_bbl_font" id="SL_bbl_font" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Tamanho da fonte"> </div> + </td> + <td class="SL_td"> + <div id="SL_bbl_help" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Ajuda"> </div> + </td> + <td class="SL_td"> + <div class="SL_pin_off" id="SL_pin" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Fixar a janela de pop-up"> </div> + </td> + </tr> +</tbody></table> +</div> +</div> + +<div id="SL_shadow_translation_result" style=""> </div> + +<div class="SL_loading" id="SL_loading" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<div id="SL_player2"> </div> + +<div id="SL_alert100">A função de fala é limitada a 200 caracteres</div> + +<div id="SL_Balloon_options" style="background: rgb(255, 255, 255) repeat scroll 0% 0%;"> +<div id="SL_arrow_down" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<table id="SL_tbl_opt" style="width: 100%;"> + <tbody><tr> + <td><input></td> + <td> + <div id="SL_BBL_IMG" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Mostrar o botão do ImTranslator 3 segundos"> </div> + </td> + <td><a class="SL_options" title="Mostrar opções">Opções</a> : <a class="SL_options" title="Histórico de tradução">Histórico</a> : <a class="SL_options" title="Comentários">Comentários</a> : <a class="SL_options" href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=GD9D8CPW8HFA2" title="Faça sua contribuição">Donate</a></td> + <td><span id="SL_Balloon_Close" title="Encerrar">Encerrar</span></td> + </tr> +</tbody></table> +</div> +</div> +</div> diff --git a/files/pt-pt/web/javascript/reference/funcionalidades_obsoletas/index.html b/files/pt-pt/web/javascript/reference/funcionalidades_obsoletas/index.html new file mode 100644 index 0000000000..9d0ae63c62 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/funcionalidades_obsoletas/index.html @@ -0,0 +1,289 @@ +--- +title: Funcionalidades obsoletas +slug: Web/JavaScript/Reference/Funcionalidades_obsoletas +tags: + - JavaScript + - Obsoleto +translation_of: Web/JavaScript/Reference/Deprecated_and_obsolete_features +--- +<div>{{JsSidebar("More")}}</div> + +<p>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).</p> + +<h2 id="Funcionalidades_obsoletas">Funcionalidades obsoletas</h2> + +<p>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..</p> + +<h3 id="Propriedades_de_RegExp">Propriedades de RegExp</h3> + +<p>The following properties are deprecated. This does not affect their use in {{jsxref("String.replace", "replacement strings", "", 1)}}:</p> + +<table class="standard-table"> + <tbody> + <tr> + <th>Propriedades</th> + <th>Descrição</th> + </tr> + <tr> + <td>{{jsxref("RegExp.n", "$1-$9")}}</td> + <td> + <p>Parenthesized substring matches, if any.<br> + <strong>Warning:</strong> Using these properties can result in problems, since browser extensions can modify them. Avoid them!</p> + </td> + </tr> + <tr> + <td>{{jsxref("RegExp.input", "$_")}}</td> + <td>See <code>input</code>.</td> + </tr> + <tr> + <td>{{jsxref("RegExp.multiline", "$*")}}</td> + <td>See <code>multiline</code>.</td> + </tr> + <tr> + <td>{{jsxref("RegExp.lastMatch", "$&")}}</td> + <td>See <code>lastMatch</code>.</td> + </tr> + <tr> + <td>{{jsxref("RegExp.lastParen", "$+")}}</td> + <td>See <code>lastParen</code>.</td> + </tr> + <tr> + <td>{{jsxref("RegExp.leftContext", "$`")}}</td> + <td>See <code>leftContext</code>.</td> + </tr> + <tr> + <td>{{jsxref("RegExp.rightContext", "$'")}}</td> + <td>See <code>rightContext</code>.</td> + </tr> + <tr> + <td>{{jsxref("RegExp.input", "input")}}</td> + <td>The string against which a regular expression is matched.</td> + </tr> + <tr> + <td>{{jsxref("RegExp.lastMatch", "lastMatch")}}</td> + <td>The last matched characters.</td> + </tr> + <tr> + <td>{{jsxref("RegExp.lastParen", "lastParen")}}</td> + <td>The last parenthesized substring match, if any.</td> + </tr> + <tr> + <td>{{jsxref("RegExp.leftContext", "leftContext")}}</td> + <td>The substring preceding the most recent match.</td> + </tr> + <tr> + <td>{{jsxref("RegExp.rightContext", "rightContext")}}</td> + <td>The substring following the most recent match.</td> + </tr> + </tbody> +</table> + +<p>The following are now properties of <code>RegExp</code> instances, no longer of the <code>RegExp</code> object:</p> + +<table class="standard-table"> + <tbody> + <tr> + <th>Propriedades</th> + <th>Descrição</th> + </tr> + <tr> + <td>{{jsxref("RegExp.global", "global")}}</td> + <td>Whether or not to test the regular expression against all possible matches in a string, or only against the first.</td> + </tr> + <tr> + <td>{{jsxref("RegExp.ignoreCase", "ignoreCase")}}</td> + <td>Whether or not to ignore case while attempting a match in a string.</td> + </tr> + <tr> + <td>{{jsxref("RegExp.lastIndex", "lastIndex")}}</td> + <td>The index at which to start the next match.</td> + </tr> + <tr> + <td>{{jsxref("RegExp.multiline", "multiline")}}</td> + <td>Whether or not to search in strings across multiple lines.</td> + </tr> + <tr> + <td>{{jsxref("RegExp.source", "source")}}</td> + <td>The text of the pattern.</td> + </tr> + </tbody> +</table> + +<h3 id="Métodos_de_egExp">Métodos de egExp</h3> + +<ul> + <li>The {{jsxref("RegExp.compile", "compile()")}} method is deprecated.</li> + <li>The <code>valueOf</code> method is no longer specialized for <code>RegExp</code>. Use {{jsxref("Object.valueOf()")}}.</li> +</ul> + +<h3 id="Propriedades_de_Function">Propriedades de <em>Function</em></h3> + +<ul> + <li>The {{jsxref("Global_Objects/Function/caller", "caller")}} and {{jsxref("Global_Objects/Function/arguments", "arguments")}} properties are deprecated, because they leak the function caller. Instead of the arguments property, you should use the {{jsxref("Functions/arguments", "arguments")}} object inside function closures.</li> +</ul> + +<h3 id="Gerador_de_Legacy">Gerador de <em>Legacy</em></h3> + +<ul> + <li>{{jsxref("Statements/Legacy_generator_function", "Legacy generator function statement")}} and {{jsxref("Operators/Legacy_generator_function", "Legacy generator function expression")}} are deprecated. Use {{jsxref("Statements/function*", "function* statement")}} and {{jsxref("Operators/function*", "function* expression")}} instead.</li> + <li>{{jsxref("Operators/Array_comprehensions", "JS1.7/JS1.8 Array comprehension", "#Differences_to_the_older_JS1.7.2FJS1.8_comprehensions")}} and {{jsxref("Operators/Generator_comprehensions", "JS1.7/JS1.8 Generator comprehension", "#Differences_to_the_older_JS1.7.2FJS1.8_comprehensions")}} are deprecated.</li> +</ul> + +<h3 id="Iterator"><em>Iterator</em></h3> + +<ul> + <li>{{jsxref("Global_Objects/StopIteration", "StopIteration")}} is deprecated.</li> + <li>{{jsxref("Global_Objects/Iterator", "Iterator")}} is deprecated.</li> +</ul> + +<h3 id="Métodos_de_Object">Métodos de <em>Object</em></h3> + +<ul> + <li>{{jsxref("Object.watch", "watch")}} and {{jsxref("Object.unwatch", "unwatch")}} are deprecated. Use {{jsxref("Proxy")}} instead.</li> + <li><code>__iterator__</code> is deprecated.</li> + <li>{{jsxref("Object.noSuchMethod", "__noSuchMethod__")}} is deprecated. Use {{jsxref("Proxy")}} instead.</li> +</ul> + +<h3 id="Métodos_de_Date">Métodos de <em>Date</em></h3> + +<ul> + <li>{{jsxref("Global_Objects/Date/getYear", "getYear")}} and {{jsxref("Global_Objects/Date/setYear", "setYear")}} are affected by the Year-2000-Problem and have been subsumed by {{jsxref("Global_Objects/Date/getFullYear", "getFullYear")}} and {{jsxref("Global_Objects/Date/setFullYear", "setFullYear")}}.</li> + <li>You should use {{jsxref("Global_Objects/Date/toISOString", "toISOString")}} instead of the deprecated {{jsxref("Global_Objects/Date/toGMTString", "toGMTString")}} method in new code.</li> + <li>{{jsxref("Global_Objects/Date/toLocaleFormat", "toLocaleFormat")}} is deprecated.</li> +</ul> + +<h3 id="Functions"><em>Functions</em></h3> + +<ul> + <li>{{jsxref("Operators/Expression_closures", "Expression closures", "", 1)}} are deprecated. Use regular {{jsxref("Operators/function", "functions")}} or {{jsxref("Functions/Arrow_functions", "arrow functions", "", 1)}} instead.</li> +</ul> + +<h3 id="Proxy"><em>Proxy</em></h3> + +<ul> + <li><a href="/en-US/docs/Archive/Web/Old_Proxy_API">Proxy.create</a> and <a href="/en-US/docs/Archive/Web/Old_Proxy_API">Proxy.createFunction</a> are deprecated. Use {{jsxref("Proxy")}} instead.</li> + <li>The following traps are obsolete: + <ul> + <li><code>hasOwn</code> ({{bug(980565)}}, Firefox 33).</li> + <li><code>getEnumerablePropertyKeys</code> ({{bug(783829)}}, Firefox 37)</li> + <li><code>getOwnPropertyNames</code> ({{bug(1007334)}}, Firefox 33)</li> + <li><code>keys</code> ({{bug(1007334)}}, Firefox 33)</li> + </ul> + </li> +</ul> + +<h3 id="Sequências_de_Escape">Sequências de <em>Escape</em></h3> + +<ul> + <li>Octal escape sequences (\ followed by one, two, or three octal digits) are deprecated in string and regular expression literals.</li> + <li>The {{jsxref("Global_Objects/escape", "escape")}} and {{jsxref("Global_Objects/unescape", "unescape")}} functions are deprecated. Use {{jsxref("Global_Objects/encodeURI", "encodeURI")}}, {{jsxref("Global_Objects/encodeURIComponent", "encodeURIComponent")}}, {{jsxref("Global_Objects/decodeURI", "decodeURI")}} or {{jsxref("Global_Objects/decodeURIComponent", "decodeURIComponent")}} to encode and decode escape sequences for special characters.</li> +</ul> + +<h3 id="Métodos_de_String">Métodos de <em>String</em></h3> + +<ul> + <li><a href="https://developer.mozilla.org/en-US/docs/tag/HTML%20wrapper%20methods">HTML wrapper methods</a> like {{jsxref("String.prototype.fontsize")}} and {{jsxref("String.prototype.big")}}.</li> + <li>{{jsxref("String.prototype.quote")}} is removed from Firefox 37.</li> + <li>non standard <code>flags</code> parameter in {{jsxref("String.prototype.search")}}, {{jsxref("String.prototype.match")}}, and {{jsxref("String.prototype.replace")}} are deprecated.</li> +</ul> + +<h2 id="Funcionalidades_removidas">Funcionalidades removidas</h2> + +<p>Estas funcionalidades obsoletas foram totalmente removidas do JavaScript e não podem mais ser utilizadas a partir da versão indicada do JavaScript.</p> + +<h3 id="Object"><em>Object</em></h3> + +<table class="standard-table"> + <tbody> + <tr> + <th>Property</th> + <th>Description</th> + </tr> + <tr> + <td>{{jsxref("Global_Objects/Object/count", "__count__")}}</td> + <td>Returns the number of enumerable properties directly on a user-defined object.</td> + </tr> + <tr> + <td>{{jsxref("Global_Objects/Object/Parent", "__parent__")}}</td> + <td>Points to an object's context.</td> + </tr> + <tr> + <td>{{jsxref("Global_Objects/Object/eval", "Object.prototype.eval()")}}</td> + <td>Evaluates a string of JavaScript code in the context of the specified object.</td> + </tr> + <tr> + <td>{{jsxref("Object.observe()")}}</td> + <td>Asynchronously observing the changes to an object.</td> + </tr> + <tr> + <td>{{jsxref("Object.unobserve()")}}</td> + <td>Remove observers.</td> + </tr> + <tr> + <td>{{jsxref("Object.getNotifier()")}}</td> + <td>Creates an object that allows to synthetically trigger a change.</td> + </tr> + </tbody> +</table> + +<h3 id="Function"><em>Function</em></h3> + +<table class="standard-table"> + <tbody> + <tr> + <th>Property</th> + <th>Description</th> + </tr> + <tr> + <td>{{jsxref("Global_Objects/Function/arity", "arity")}}</td> + <td>Number of formal arguments.</td> + </tr> + </tbody> +</table> + +<h3 id="Array"><em>Array</em></h3> + +<table class="standard-table"> + <tbody> + <tr> + <td>Property</td> + <td>Description</td> + </tr> + <tr> + <td>{{jsxref("Array.observe()")}}</td> + <td>Asynchronously observing changes to Arrays.</td> + </tr> + <tr> + <td>{{jsxref("Array.unobserve()")}}</td> + <td>Remove observers.</td> + </tr> + </tbody> +</table> + +<h3 id="Number"><em>Number</em></h3> + +<ul> + <li>{{jsxref("Number.toInteger()")}}</li> +</ul> + +<h3 id="ParallelArray"><em>ParallelArray</em></h3> + +<ul> + <li>{{jsxref("ParallelArray")}}</li> +</ul> + +<h3 id="Statements"><em>Statements</em></h3> + +<ul> + <li>{{jsxref("Statements/for_each...in", "for each...in")}} is deprecated. Use {{jsxref("Statements/for...of", "for...of")}} instead.</li> + <li>Destructuring {{jsxref("Statements/for...in", "for...in")}} is deprecated. Use {{jsxref("Statements/for...of", "for...of")}} instead.</li> + <li>let blocks and let expressions are obsolete.</li> +</ul> + +<h3 id="E4X">E4X</h3> + +<p>See <a href="/en-US/docs/Archive/Web/E4X">E4X</a> for more information.</p> + +<h3 id="Variáveis_Sharp">Variáveis <em>Sharp</em></h3> + +<p>Consulte <a href="/en-US/docs/Archive/Web/Sharp_variables_in_JavaScript">Sharp variables in JavaScript</a> para mais informação.</p> diff --git a/files/pt-pt/web/javascript/reference/funcoes/arguments/index.html b/files/pt-pt/web/javascript/reference/funcoes/arguments/index.html new file mode 100644 index 0000000000..c7ac84a4b9 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/funcoes/arguments/index.html @@ -0,0 +1,228 @@ +--- +title: O objeto arguments +slug: Web/JavaScript/Reference/Funcoes/arguments +tags: + - Class + - Funções + - JavaScript + - Referencia + - arguments +translation_of: Web/JavaScript/Reference/Functions/arguments +--- +<p>{{JSSidebar("Functions")}}</p> + +<p><strong><code>arguments</code></strong> é um objeto semelhante a uma "<code>Matiz</code>" acessível dentro de <em>functions </em>que contém os valores dos argumentos passados para essa função.</p> + +<div class="blockIndicator note"> +<p><strong>Nota:</strong> If you're writing ES6 compatible code, then <a href="/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters">rest parameters</a> should be preferred.</p> +</div> + +<div class="blockIndicator note"> +<p><strong>Nota:</strong> “Array-like” means that <code>arguments</code> has a <code><a href="/en-US/docs/Web/JavaScript/Reference/Functions/arguments/length">length</a></code> property and properties indexed from zero, but it doesn't have {{JSxRef("Array")}}'s built-in methods like <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach">forEach</a></code> and <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map">map</a></code>. See <a href="#Description">§Description</a> for details.</p> +</div> + +<div>{{EmbedInteractiveExample("pages/js/functions-arguments.html")}}</div> + + + +<h2 id="Sintaxe">Sintaxe</h2> + +<pre class="syntaxbox">arguments</pre> + +<h2 id="Descrição">Descrição</h2> + +<p>The <code>arguments</code> object is a local variable available within all non-<a href="/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions">arrow</a> functions. You can refer to a function's arguments inside that function by using its <code>arguments</code> object. It has entries for each argument the function was called with, with the first entry's index at 0.</p> + +<p>For example, if a function is passed 3 arguments, you can access them as follows:</p> + +<pre class="brush: js">arguments[0] // first argument +arguments[1] // second argument +arguments[2] // third argument +</pre> + +<p>Each argument can also be set or reassigned:</p> + +<pre class="brush: js">arguments[1] = 'new value'; +</pre> + +<p>The <code>arguments</code> object is not an {{JSxRef("Array")}}. It is similar, but does not have any <code>Array</code> properties except <code><a href="/en-US/docs/Web/JavaScript/Reference/Functions/arguments/length">length</a></code>. For example, it does not have the <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/pop">pop</a></code> method. However, it can be converted to a real <code>Array</code>:</p> + +<pre class="brush: js">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); +</pre> + +<p>As you can do with any Array-like object, you can use ES2015's {{JSxRef("Array.from()")}} method or <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator">spread operator</a> to convert <code>arguments</code> to a real Array:</p> + +<pre>let args = Array.from(arguments); +// or +let args = [...arguments];</pre> + +<p>The <code>arguments</code> 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 <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/min">Math.min()</a></code>. This example function accepts any number of string arguments and returns the longest one:</p> + +<pre class="brush: js">function longestString() { + var longest = ''; + for (var i=0; i < arguments.length; i++) { + if (arguments[i].length > longest.length) { + longest = arguments[i]; + } + } + return longest; +} +</pre> + +<p>You can use <code><a href="/en-US/docs/JavaScript/Reference/Functions_and_function_scope/arguments/length">arguments.length</a></code> 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 <code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Function/length">length</a></code> property.</p> + +<h3 id="Utilizar_typeof_com_Arguments">Utilizar <code>typeof</code> com <em>Arguments</em></h3> + +<p>The <code><a href="/en-US/docs/Web/JavaScript/Reference/Operators/typeof">typeof</a></code> operator returns <code>'object'</code> when used with <code>arguments</code></p> + +<pre class="brush: js">console.log(typeof arguments); // 'object' </pre> + +<p>The type of individual arguments can be determined by indexing <code>arguments</code>:</p> + +<pre>console.log(typeof arguments[0]); // returns the type of the first argument</pre> + +<h2 id="Propriedades">Propriedades</h2> + +<dl> + <dt></dt> + <dt>{{jsxref("Functions/arguments/callee", "arguments.callee")}}</dt> + <dd>Reference to the currently executing function that the arguments belong to.</dd> + <dt>{{jsxref("Functions/arguments/length", "arguments.length")}}</dt> + <dd>The number of arguments that were passed to the function.</dd> + <dt>{{jsxref("Functions/arguments/@@iterator", "arguments[@@iterator]")}}</dt> + <dd>Returns a new {{jsxref("Array/@@iterator", "Array iterator", "", 0)}} object that contains the values for each index in <code>arguments</code>.</dd> +</dl> + +<h2 id="Exemplos">Exemplos</h2> + +<h3 id="Definir_uma_function_que_concatena_várias_strings">Definir uma <em>function</em> que concatena várias <em>strings</em></h3> + +<p>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.</p> + +<pre class="brush:js">function myConcat(separator) { + var args = Array.prototype.slice.call(arguments, 1); + return args.join(separator); +}</pre> + +<p>You can pass as many arguments as you like to this function. It returns a string list using each argument in the list:</p> + +<pre class="brush:js">// 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');</pre> + +<h3 id="Definir_uma_function_que_cria_listas_HTML">Definir uma <em>function</em> que cria listas HTML</h3> + +<p>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 "<code>u</code>" if the list is to be unordered (bulleted), or "<code>o</code>" if the list is to be ordered (numbered). The function is defined as follows:</p> + +<pre class="brush:js">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; +}</pre> + +<p>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:</p> + +<pre class="brush:js">var listHTML = list('u', 'One', 'Two', 'Three'); + +/* listHTML is: +"<ul><li>One</li><li>Two</li><li>Three</li></ul>" +*/</pre> + +<h3 id="Parâmetros_Rest_predefinição_e_desestruturados">Parâmetros Rest, predefinição, e desestruturados</h3> + +<p>The <code>arguments</code> object can be used in conjunction with <a href="/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters">rest</a>, <a href="/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters">default</a>, and <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment">destructured</a> parameters.</p> + +<pre class="brush: js">function foo(...args) { + return args; +} +foo(1, 2, 3); // [1,2,3] +</pre> + +<p>While the presence of rest, default, or destructured parameters does not alter the <a href="/en-US/docs/Web/JavaScript/Reference/Strict_mode#Making_eval_and_arguments_simpler">behavior of the <code>arguments</code> object in strict mode code</a>, there is a subtle difference for non-strict code.</p> + +<p>In strict-mode code, the <code>arguments</code> 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 <code>arguments</code> object. Nor will assigning new variables to the <code>arguments</code> object affect the value of variables.</p> + +<div class="blockIndicator note"> +<p><strong>Nota:</strong> You cannot write a <code>"use strict";</code> directive in the body of a function definition that accepts rest, default, or destructured parameters. Doing so will throw <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Strict_Non_Simple_Params">a syntax error</a>.</p> +</div> + +<p>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 <code>arguments</code> object, and vice versa:</p> + +<pre class="brush: js">function func(a) { + arguments[0] = 99; // updating arguments[0] also updates a + console.log(a); +} +func(10); // 99 +</pre> + +<p>And also:</p> + +<pre class="brush: js">function func(a) { + a = 99; // updating a also updates arguments[0] + console.log(arguments[0]); +} +func(10); // 99 +</pre> + +<p>Conversely, non-strict functions that <strong>are</strong> passed rest, default, or destructured parameters <strong>will not</strong> sync new values assigned to argument variables in the function body with the <code>arguments</code> object. Instead, the <code>arguments</code> object in non-strict functions with complex parameters <strong>will always</strong> 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):</p> + +<pre class="brush: js">function func(a = 55) { + arguments[0] = 99; // updating arguments[0] does not also update a + console.log(a); +} +func(10); // 10</pre> + +<p>E também:</p> + +<pre class="brush: js">function func(a = 55) { + a = 99; // updating a does not also update arguments[0] + console.log(arguments[0]); +} +func(10); // 10 +</pre> + +<p>E também:</p> + +<pre class="brush: js">// An untracked default parameter +function func(a = 55) { + console.log(arguments[0]); +} +func(); // undefined</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificação</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('ESDraft', '#sec-arguments-exotic-objects', 'Arguments Exotic Objects')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibildiade_de_navegador">Compatibildiade de navegador</h2> + + + +<p>{{Compat("javascript.functions.arguments")}}</p> + +<h2 id="Consulte_também">Consulte também</h2> + +<ul> + <li>{{JSxRef("Function")}}</li> + <li><a href="/pt-PT/docs/Web/JavaScript/Reference/Funcoes/parametros_rest">Parâmetros Rest</a></li> +</ul> diff --git a/files/pt-pt/web/javascript/reference/funcoes/funcoes_seta/index.html b/files/pt-pt/web/javascript/reference/funcoes/funcoes_seta/index.html new file mode 100644 index 0000000000..aa7b7b3121 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/funcoes/funcoes_seta/index.html @@ -0,0 +1,399 @@ +--- +title: Expressões da função "Seta" +slug: Web/JavaScript/Reference/Funcoes/Funcoes_seta +translation_of: Web/JavaScript/Reference/Functions/Arrow_functions +--- +<div>{{jsSidebar("Functions")}}</div> + +<p>Uma <strong>expressão da função seta</strong> é uma alternativa sintaticamente compacta a uma expressão de <a href="/pt-PT/docs/Web/JavaScript/Reference/Operadores/função">expressão de função</a> regular, embora sem as suas próprias associações às palavras-chave <code><a href="/en-US/docs/Web/JavaScript/Reference/Operators/this">this</a></code>, <code><a href="/en-US/docs/Web/JavaScript/Reference/Functions/arguments">arguments</a></code>, <code><a href="/en-US/docs/Web/JavaScript/Reference/Operators/super">super</a></code>, ou <code><a href="/en-US/docs/Web/JavaScript/Reference/Operators/new.target">new.target</a></code>. As expressões de função (<em>function</em>) de seta são inadequadas como métodos, e não podem ser utilziadas como construtores.</p> + +<div>{{EmbedInteractiveExample("pages/js/functions-arrow.html")}}</div> + +<h2 id="Sintaxe">Sintaxe</h2> + +<h3 id="Basic_syntax">Basic syntax</h3> + +<pre class="syntaxbox">(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 } +</pre> + +<h3 id="Advanced_syntax">Advanced syntax</h3> + +<pre class="syntaxbox">// Parenthesize the body of a function to return an object literal expression: +params => ({foo: bar}) + +// <a href="/en-US/docs/Web/JavaScript/Reference/Functions/Rest_parameters">Rest parameters</a> and <a href="/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters">default parameters</a> are supported +(param1, param2, ...rest) => { statements } +(param1 = defaultValue1, param2, …, paramN = defaultValueN) => { +statements } + +// <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment">Destructuring</a> within the parameter list is also supported +var f = ([a, b] = [1, 2], {x: c} = {x: a + b}) => a + b + c; +f(); // 6 +</pre> + +<h2 id="Descrição">Descrição</h2> + +<p>See also <a href="https://hacks.mozilla.org/2015/06/es6-in-depth-arrow-functions/">"ES6 In Depth: Arrow functions" on hacks.mozilla.org</a>.</p> + +<p>Two factors influenced the introduction of arrow functions: the need for shorter functions and the behavior of the <code>this</code> keyword.</p> + +<h3 id="Funções_curtas">Funções curtas</h3> + +<pre class="brush: js">var elements = [ + 'Hydrogen', + 'Helium', + 'Lithium', + 'Beryllium' +]; + +// This statement returns the array: [8, 6, 7, 9] +elements.<a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map">map</a>(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.<a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map">map</a>(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.<a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map">map</a>(({ 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.<a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map">map</a>(({ length }) => length); // [8, 6, 7, 9] +</pre> + +<h3 id="No_separate_this">No separate <code>this</code></h3> + +<p>Before arrow functions, every new function defined its own <code><a href="/en-US/docs/Web/JavaScript/Reference/Operators/this">this</a></code> value based on how the function was called:</p> + +<ul> + <li>A new object in the case of a constructor.</li> + <li><code>undefined</code> in <a href="/en-US/docs/Web/JavaScript/Reference/Strict_mode">strict mode</a> function calls.</li> + <li>The base object if the function was called as an "object method".</li> + <li>etc.</li> +</ul> + +<p>This proved to be less than ideal with an object-oriented style of programming.</p> + +<pre class="brush: js">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();</pre> + +<p>In ECMAScript 3/5, the <code>this</code> issue was fixable by assigning the value in <code>this</code> to a variable that could be closed over.</p> + +<pre class="brush: js">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); +}</pre> + +<p>Alternatively, a <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind">bound function</a> could be created so that a preassigned <code>this</code> value would be passed to the bound target function (the <code>growUp()</code> function in the example above).</p> + +<p>An arrow function does not have its own <code>this</code>. The <code>this</code> value of the enclosing lexical scope is used; arrow functions follow the normal variable lookup rules. So while searching for <code>this</code> which is not present in current scope, an arrow function ends up finding the <code>this</code> from its enclosing scope.</p> + +<p>Thus, in the following code, the <code>this</code> within the function that is passed to <code>setInterval</code> has the same value as the <code>this</code> in the lexically enclosing function:</p> + +<pre class="brush: js">function Person(){ + this.age = 0; + + setInterval(() => { + this.age++; // |this| properly refers to the Person object + }, 1000); +} + +var p = new Person();</pre> + +<h4 id="Relation_with_strict_mode">Relation with strict mode</h4> + +<p>Given that <code>this</code> comes from the surrounding lexical context, <a href="/en-US/docs/Web/JavaScript/Reference/Strict_mode">strict mode</a> rules with regard to <code>this</code> are ignored.</p> + +<pre class="brush: js">var f = () => { 'use strict'; return this; }; +f() === window; // or the global object</pre> + +<p>All other strict mode rules apply normally.</p> + +<h4 id="Invoked_through_call_or_apply">Invoked through call or apply</h4> + +<p>Since arrow functions do not have their own <code>this</code>, the methods <code>call()</code> and <code>apply()</code> can only pass in parameters. Any <code>this</code> argument is ignored.</p> + +<pre class="brush: js">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</pre> + +<h3 id="No_binding_of_arguments">No binding of <code>arguments</code></h3> + +<p>Arrow functions do not have their own <a href="/en-US/docs/Web/JavaScript/Reference/Functions/arguments"><code>arguments</code> object</a>. Thus, in this example, <code>arguments</code> is simply a reference to the arguments of the enclosing scope:</p> + +<pre class="brush: js">var arguments = [1, 2, 3]; +var arr = () => arguments[0]; + +arr(); // 1 + +function foo(n) { + var f = () => arguments[0] + n; // <em>foo</em>'s implicit arguments binding. arguments[0] is n + return f(); +} + +foo(3); // 6</pre> + +<p>In most cases, using <a href="/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters">rest parameters</a> is a good alternative to using an <code>arguments</code> object.</p> + +<pre class="brush: js">function foo(n) { + var f = (...args) => args[0] + n; + return f(10); +} + +foo(1); // 11</pre> + +<h3 id="Arrow_functions_used_as_methods">Arrow functions used as methods</h3> + +<p>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:</p> + +<pre class="brush: js">'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 {...}</pre> + +<p>Arrow functions do not have their own <code>this</code>. Another example involving {{jsxref("Object.defineProperty()")}}:</p> + +<pre class="brush: js">'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' + } +}); +</pre> + +<h3 id="Use_of_the_new_operator">Use of the <code>new</code> operator</h3> + +<p>Arrow functions cannot be used as constructors and will throw an error when used with <code>new</code>.</p> + +<pre class="brush: js">var Foo = () => {}; +var foo = new Foo(); // TypeError: Foo is not a constructor</pre> + +<h3 id="Use_of_prototype_property">Use of <code>prototype</code> property</h3> + +<p>Arrow functions do not have a <code>prototype</code> property.</p> + +<pre class="brush: js">var Foo = () => {}; +console.log(Foo.prototype); // undefined +</pre> + +<h3 id="Use_of_the_yield_keyword">Use of the <code>yield</code> keyword</h3> + +<p>The <code><a href="/en-US/docs/Web/JavaScript/Reference/Operators/yield">yield</a></code> 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.</p> + +<h2 id="Function_body">Function body</h2> + +<p>Arrow functions can have either a "concise body" or the usual "block body".</p> + +<p>In a concise body, only an expression is specified, which becomes the implicit return value. In a block body, you must use an explicit <code>return</code> statement.</p> + +<pre class="brush: js">var func = x => x * x; +// concise body syntax, implied "return" + +var func = (x, y) => { return x + y; }; +// with block body, explicit "return" needed +</pre> + +<h2 id="Returning_object_literals">Returning object literals</h2> + +<p>Keep in mind that returning object literals using the concise body syntax <code>params => {object:literal}</code> will not work as expected.</p> + +<pre class="brush: js">var func = () => { foo: 1 }; +// Calling func() returns undefined! + +var func = () => { foo: function() {} }; +// SyntaxError: function statement requires a name</pre> + +<p>This is because the code inside braces ({}) is parsed as a sequence of statements (i.e. <code>foo</code> is treated like a label, not a key in an object literal).</p> + +<p>You must wrap the object literal in parentheses:</p> + +<pre class="brush: js">var func = () => ({ foo: 1 });</pre> + +<h2 id="Line_breaks">Line breaks</h2> + +<p>An arrow function cannot contain a line break between its parameters and its arrow.</p> + +<pre class="brush: js">var func = (a, b, c) + => 1; +// SyntaxError: expected expression, got '=>'</pre> + +<p>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.</p> + +<pre class="brush: js">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</pre> + +<h2 id="Parsing_order">Parsing order</h2> + +<p>Although the arrow in an arrow function is not an operator, arrow functions have special parsing rules that interact differently with <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence">operator precedence</a> compared to regular functions.</p> + +<pre class="brush: js">let callback; + +callback = callback || function() {}; // ok + +callback = callback || () => {}; +// SyntaxError: invalid arrow-function arguments + +callback = callback || (() => {}); // ok +</pre> + +<h2 id="More_examples">More examples</h2> + +<pre class="brush: js">// An empty arrow function returns undefined +let empty = () => {}; + +(() => 'foobar')(); +// Returns "foobar" +// (this is an <a href="/en-US/docs/Glossary/IIFE">Immediately Invoked Function Expression</a>) + +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); +</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-arrow-function-definitions', 'Arrow Function Definitions')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div> + + +<p>{{Compat("javascript.functions.arrow_functions")}}</p> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="https://hacks.mozilla.org/2015/06/es6-in-depth-arrow-functions/">"ES6 In Depth: Arrow functions" on hacks.mozilla.org</a></li> +</ul> diff --git a/files/pt-pt/web/javascript/reference/funcoes/index.html b/files/pt-pt/web/javascript/reference/funcoes/index.html new file mode 100644 index 0000000000..02b35fc7bd --- /dev/null +++ b/files/pt-pt/web/javascript/reference/funcoes/index.html @@ -0,0 +1,594 @@ +--- +title: Funções +slug: Web/JavaScript/Reference/Funcoes +tags: + - Constructor + - Função + - Funções + - JavaScript + - Parâmetro + - parâmetros +translation_of: Web/JavaScript/Reference/Functions +--- +<div>{{jsSidebar("Functions")}}</div> + +<p>Generally speaking, a function is a "subprogram" that can be <em>called</em> 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 <em>function body</em>. Values can be <em>passed</em> to a function, and the function will <em>return</em> a value.</p> + +<p>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 <code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Function">Function</a></code> objects.</p> + +<p>For more examples and explanations, see also the <a href="/en-US/docs/Web/JavaScript/Guide/Functions">JavaScript guide about functions</a>.</p> + +<h2 id="Descrição">Descrição</h2> + +<p>Every function in JavaScript is a <code>Function</code> object. See {{jsxref("Function")}} for information on properties and methods of <code>Function</code> objects.</p> + +<p>To return a value other than the default, a function must have a <code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/return">return</a></code> statement that specifies the value to return. A function without a return statement will return a default value. In the case of a <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/constructor">constructor</a> called with the <code><a href="/en-US/docs/Web/JavaScript/Reference/Operators/new">new</a></code> keyword, the default value is the value of its <code>this</code> parameter. For all other functions, the default return value is {{jsxref("undefined")}}.</p> + +<p>The parameters of a function call are the function's <em>arguments</em>. Arguments are passed to functions <em>by value</em>. 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:</p> + +<pre class="brush: js">/* 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); +</pre> + +<p>The <a href="/en-US/docs/Web/JavaScript/Reference/Operators/this"><code>this</code> keyword</a> does not refer to the currently executing function, so you must refer to <code>Function</code> objects by name, even within the function body.</p> + +<h2 id="Definindo_funções">Definindo funções</h2> + +<p>There are several ways to define functions:</p> + +<h3 id="The_function_declaration_(function_statement)">The function declaration (<code>function</code> statement)</h3> + +<p>There is a special syntax for declaring functions (see <a href="/en-US/docs/Web/JavaScript/Reference/Statements/function">function statement</a> for details):</p> + +<pre class="syntaxbox">function <em>name</em>([<em>param</em>[, <em>param</em>[, ... <em>param</em>]]]) { + <em>statements</em> +} +</pre> + +<dl> + <dt><code>name</code></dt> + <dd>The function name.</dd> +</dl> + +<dl> + <dt><code>param</code></dt> + <dd>The name of an argument to be passed to the function. A function can have up to 255 arguments.</dd> +</dl> + +<dl> + <dt><code>statements</code></dt> + <dd>The statements comprising the body of the function.</dd> +</dl> + +<h3 id="The_function_expression_(function_expression)">The function expression (<code>function</code> expression)</h3> + +<p>A function expression is similar to and has the same syntax as a function declaration (see <a href="/en-US/docs/Web/JavaScript/Reference/Operators/function">function expression</a> 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 <em>hoisted</em> onto the beginning of the scope, therefore they cannot be used before they appear in the code.</p> + +<pre class="syntaxbox">function [<em>name</em>]([<em>param</em>[, <em>param</em>[, ... <em>param</em>]]]) { + <em>statements</em> +} +</pre> + +<dl> + <dt><code>name</code></dt> + <dd>The function name. Can be omitted, in which case the function becomes known as an anonymous function.</dd> +</dl> + +<dl> + <dt><code>param</code></dt> + <dd>The name of an argument to be passed to the function. A function can have up to 255 arguments.</dd> + <dt><code>statements</code></dt> + <dd>The statements comprising the body of the function.</dd> +</dl> + +<p>Here is an example of an <strong>anonymous</strong> function expression (the <code>name</code> is not used):</p> + +<pre class="brush: js">var myFunction = function() { + statements +}</pre> + +<p>It is also possible to provide a name inside the definition in order to create a <strong>named</strong> function expression:</p> + +<pre class="brush: js">var myFunction = function namedFunction(){ + statements +} +</pre> + +<p>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.</p> + +<p>As we can see, both examples do not start with the <code>function</code> keyword. Statements involving functions which do not start with <code>function</code> are function expressions.</p> + +<p>When functions are used only once, a common pattern is an <strong>IIFE (<em>Immediately Invokable Function Expression</em>)</strong>.</p> + +<pre class="brush: js">(function() { + statements +})();</pre> + +<p>IIFE are function expressions that are invoked as soon as the function is declared.</p> + +<h3 id="The_generator_function_declaration_(function*_statement)">The generator function declaration (<code>function*</code> statement)</h3> + +<p>There is a special syntax for generator function declarations (see {{jsxref('Statements/function*', 'function* statement')}} for details):</p> + +<pre class="syntaxbox">function* <em>name</em>([<em>param</em>[, <em>param</em>[, ... <em>param</em>]]]) { + <em>statements</em> +} +</pre> + +<dl> + <dt><code>name</code></dt> + <dd>The function name.</dd> +</dl> + +<dl> + <dt><code>param</code></dt> + <dd>The name of an argument to be passed to the function. A function can have up to 255 arguments.</dd> +</dl> + +<dl> + <dt><code>statements</code></dt> + <dd>The statements comprising the body of the function.</dd> +</dl> + +<h3 id="The_generator_function_expression_(function*_expression)">The generator function expression (<code>function*</code> expression)</h3> + +<p>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):</p> + +<pre class="syntaxbox">function* [<em>name</em>]([<em>param</em>[, <em>param</em>[, ... <em>param</em>]]]) { + <em>statements</em> +} +</pre> + +<dl> + <dt><code>name</code></dt> + <dd>The function name. Can be omitted, in which case the function becomes known as an anonymous function.</dd> +</dl> + +<dl> + <dt><code>param</code></dt> + <dd>The name of an argument to be passed to the function. A function can have up to 255 arguments.</dd> + <dt><code>statements</code></dt> + <dd>The statements comprising the body of the function.</dd> +</dl> + +<h3 id="The_arrow_function_expression_(>)">The arrow function expression (=>)</h3> + +<p>An arrow function expression has a shorter syntax and lexically binds its <code>this</code> value (see <a href="/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions">arrow functions</a> for details):</p> + +<pre class="syntaxbox">([param[, param]]) => { + statements +} + +param => expression +</pre> + +<dl> + <dt><code>param</code></dt> + <dd>The name of an argument. Zero arguments need to be indicated with <code>()</code>. For only one argument, the parentheses are not required. (like <code>foo => 1</code>)</dd> + <dt><code>statements or expression</code></dt> + <dd>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.</dd> +</dl> + +<h3 id="The_Function_constructor">The <code>Function</code> constructor</h3> + +<div class="note"> +<p><strong>Note:</strong> Using the <code>Function</code> 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.</p> +</div> + +<p>As all other objects, {{jsxref("Function")}} objects can be created using the <code>new</code> operator:</p> + +<pre class="syntaxbox">new Function (<em>arg1</em>, <em>arg2</em>, ... <em>argN</em>, <em>functionBody</em>) +</pre> + +<dl> + <dt><code>arg1, arg2, ... arg<em>N</em></code></dt> + <dd>Zero or more names to be used by the function as formal parameters. Each must be a proper JavaScript identifier.</dd> +</dl> + +<dl> + <dt><code>functionBody</code></dt> + <dd>A string containing the JavaScript statements comprising the function body.</dd> +</dl> + +<p>Invoking the <code>Function</code> constructor as a function (without using the <code>new</code> operator) has the same effect as invoking it as a constructor.</p> + +<h3 id="The_GeneratorFunction_constructor">The <code>GeneratorFunction</code> constructor</h3> + +<div class="note"> +<p><strong>Note:</strong> <code>GeneratorFunction</code> is not a global object, but could be obtained from generator function instance (see {{jsxref("GeneratorFunction")}} for more detail).</p> +</div> + +<div class="note"> +<p><strong>Note:</strong> Using the <code>GeneratorFunction</code> 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.</p> +</div> + +<p>As all other objects, {{jsxref("GeneratorFunction")}} objects can be created using the <code>new</code> operator:</p> + +<pre class="syntaxbox">new GeneratorFunction (<em>arg1</em>, <em>arg2</em>, ... <em>argN</em>, <em>functionBody</em>) +</pre> + +<dl> + <dt><code>arg1, arg2, ... arg<em>N</em></code></dt> + <dd>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 "<code>x</code>", "<code>theValue</code>", or "<code>a,b</code>".</dd> +</dl> + +<dl> + <dt><code>functionBody</code></dt> + <dd>A string containing the JavaScript statements comprising the function definition.</dd> +</dl> + +<p>Invoking the <code>Function</code> constructor as a function (without using the <code>new</code> operator) has the same effect as invoking it as a constructor.</p> + +<h2 id="Parâmetros_de_função">Parâmetros de função</h2> + +<h3 id="Parâmetros_predefinidos">Parâmetros predefinidos</h3> + +<p>Default function parameters allow formal parameters to be initialized with default values if no value or <code>undefined</code> is passed. For more details, see<a href="/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters"> default parameters</a>.</p> + +<h3 id="Parâmetros_Rest">Parâmetros <em>Rest</em></h3> + +<p>The rest parameter syntax allows to represent an indefinite number of arguments as an array. For more details, see <a href="/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters">rest parameters</a>.</p> + +<h2 id="O_objeto_arguments">O objeto <em><code>arguments</code></em></h2> + +<p>You can refer to a function's arguments within the function by using the <code>arguments</code> object. See <a href="/en-US/docs/Web/JavaScript/Reference/Functions/arguments">arguments</a>.</p> + +<ul> + <li><code><a href="/en-US/docs/JavaScript/Reference/Functions_and_function_scope/arguments">arguments</a></code>: An array-like object containing the arguments passed to the currently executing function.</li> + <li><code><a href="/en-US/docs/JavaScript/Reference/Functions_and_function_scope/arguments/callee">arguments.callee</a></code> {{Deprecated_inline}}: The currently executing function.</li> + <li><code><a href="/en-US/docs/JavaScript/Reference/Functions_and_function_scope/arguments/caller">arguments.caller</a></code> {{Obsolete_inline}} : The function that invoked the currently executing function.</li> + <li><code><a href="/en-US/docs/JavaScript/Reference/Functions_and_function_scope/arguments/length">arguments.length</a></code>: The number of arguments passed to the function.</li> +</ul> + +<h2 id="Definindo_funções_de_método">Definindo funções de método</h2> + +<h3 id="Getter_and_setter_functions">Getter and setter functions</h3> + +<p>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.</p> + +<dl> + <dt><a href="/en-US/docs/Web/JavaScript/Reference/Functions/get">get</a></dt> + <dd> + <p>Binds an object property to a function that will be called when that property is looked up.</p> + </dd> + <dt><a href="/en-US/docs/Web/JavaScript/Reference/Functions/set">set</a></dt> + <dd>Binds an object property to a function to be called when there is an attempt to set that property.</dd> +</dl> + +<h3 id="Method_definition_syntax">Method definition syntax</h3> + +<p>Starting with ECMAScript 2015, you are able to define own methods in a shorter syntax, similar to the getters and setters. See <a href="/en-US/docs/Web/JavaScript/Reference/Functions/Method_definitions">method definitions</a> for more information.</p> + +<pre class="brush: js">var obj = { + foo() {}, + bar() {} +};</pre> + +<h2 id="Constructor_vs._declaration_vs._expression">Constructor vs. declaration vs. expression</h2> + +<p>Compare the following:</p> + +<p>A function defined with the <code>Function</code> <em>constructor</em> assigned to the variable <code>multiply:</code></p> + +<pre class="brush: js">var multiply = new Function('x', 'y', 'return x * y');</pre> + +<p>A <em>function declaration</em> of a function named <code>multiply</code>:</p> + +<pre class="brush: js">function multiply(x, y) { + return x * y; +} // there is no semicolon here +</pre> + +<p>A <em>function expression</em> of an anonymous function assigned to the variable <code>multiply:</code></p> + +<pre class="brush: js">var multiply = function(x, y) { + return x * y; +}; +</pre> + +<p>A <em>function expression</em> of a function named <code>func_name</code> assigned to the variable <code>multiply:</code></p> + +<pre class="brush: js">var multiply = function func_name(x, y) { + return x * y; +}; +</pre> + +<h3 id="Differences">Differences</h3> + +<p>All do approximately the same thing, with a few subtle differences:</p> + +<p>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 <code>undefined</code> if the function name was previously declared via a <code>var</code> statement). For example:</p> + +<pre class="brush: js">var y = function x() {}; +alert(x); // throws an error +</pre> + +<p>The function name also appears when the function is serialized via <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/toString"><code>Function</code>'s toString method</a>.</p> + +<p>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.</p> + +<p>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:</p> + +<p>A function defined by '<code>new Function'</code> does not have a function name. However, in the <a href="/en-US/docs/Mozilla/Projects/SpiderMonkey">SpiderMonkey</a> JavaScript engine, the serialized form of the function shows as if it has the name "anonymous". For example, <code>alert(new Function())</code> outputs:</p> + +<pre class="brush: js">function anonymous() { +} +</pre> + +<p>Since the function actually does not have a name, <code>anonymous</code> is not a variable that can be accessed within the function. For example, the following would result in an error:</p> + +<pre class="brush: js">var foo = new Function("alert(anonymous);"); +foo(); +</pre> + +<p>Unlike functions defined by function expressions or by the <code>Function</code> constructor, a function defined by a function declaration can be used before the function declaration itself. For example:</p> + +<pre class="brush: js">foo(); // alerts FOO! +function foo() { + alert('FOO!'); +} +</pre> + +<p>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 <code>Function</code> constructor does not inherit any scope other than the global scope (which all functions inherit).</p> + +<pre class="brush: js">/* + * 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) + */ +</pre> + +<p>Functions defined by function expressions and function declarations are parsed only once, while those defined by the <code>Function</code> constructor are not. That is, the function body string passed to the <code>Function</code> 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 "<code>new Function(...)</code>". Therefore the <code>Function</code> constructor should generally be avoided whenever possible.</p> + +<p>It should be noted, however, that function expressions and function declarations nested within the function generated by parsing a <code>Function constructor</code> 's string aren't parsed repeatedly. For example:</p> + +<pre class="brush: js">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.</pre> + +<p>A function declaration is very easily (and often unintentionally) turned into a function expression. A function declaration ceases to be one when it either:</p> + +<ul> + <li>becomes part of an expression</li> + <li>is no longer a "source element" of a function or the script itself. A "source element" is a non-nested statement in the script or a function body:</li> +</ul> + +<pre class="brush: js">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 + } +} +</pre> + +<h3 id="Examples">Examples</h3> + +<pre class="brush: js">// 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() {} + } +} +</pre> + +<h2 id="Block-level_functions">Block-level functions</h2> + +<p>In <a href="/en-US/docs/Web/JavaScript/Reference/Strict_mode">strict mode</a>, starting with ES2015, functions inside blocks are now scoped to that block. Prior to ES2015, block-level functions were forbidden in strict mode.</p> + +<pre class="brush: js">'use strict'; + +function f() { + return 1; +} + +{ + function f() { + return 2; + } +} + +f() === 1; // true + +// f() === 2 in non-strict mode +</pre> + +<h3 id="Block-level_functions_in_non-strict_code">Block-level functions in non-strict code</h3> + +<p>In a word: Don't.</p> + +<p>In non-strict code, function declarations inside blocks behave strangely. For example:</p> + +<pre class="brush: js">if (shouldDefineZero) { + function zero() { // DANGER: compatibility risk + console.log("This is zero."); + } +} +</pre> + +<p>ES2015 says that if <code>shouldDefineZero</code> is false, then <code>zero</code> 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 <code>zero</code> whether the block executed or not.</p> + +<p>In <a href="/en-US/docs/Web/JavaScript/Reference/Strict_mode">strict mode</a>, all browsers that support ES2015 handle this the same way: <code>zero</code> is defined only if <code>shouldDefineZero</code> is true, and only in the scope of the <code>if</code>-block.</p> + +<p>A safer way to define functions conditionally is to assign a function expression to a variable:</p> + +<pre class="brush: js">var zero; +if (shouldDefineZero) { + zero = function() { + console.log("This is zero."); + }; +} +</pre> + +<h2 id="Exemplos">Exemplos</h2> + +<h3 id="Returning_a_formatted_number">Returning a formatted number</h3> + +<p>The following function returns a string containing the formatted representation of a number padded with leading zeros.</p> + +<pre class="brush: js">// 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; +} +</pre> + +<p>The following statements call the padZeros function.</p> + +<pre class="brush: js">var result; +result = padZeros(42,4); // returns "0042" +result = padZeros(42,2); // returns "42" +result = padZeros(5,4); // returns "0005" +</pre> + +<h3 id="Determining_whether_a_function_exists">Determining whether a function exists</h3> + +<p>You can determine whether a function exists by using the <code>typeof</code> operator. In the following example, a test is performed to determine if the <code>window</code> object has a property called <code>noFunc</code> that is a function. If so, it is used; otherwise some other action is taken.</p> + +<pre class="brush: js"> if ('function' === typeof window.noFunc) { + // use noFunc() + } else { + // do something else + } +</pre> + +<p>Note that in the <code>if</code> test, a reference to <code>noFunc</code> is used—there are no brackets "()" after the function name so the actual function is not called.</p> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.0</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-13', 'Function Definition')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-function-definitions', 'Function definitions')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>New: Arrow functions, Generator functions, default parameters, rest parameters.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-function-definitions', 'Function definitions')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_de_navegador">Compatibilidade de navegador</h2> + + + +<p>{{Compat("javascript.functions")}}</p> + +<h2 id="Consulte_também">Consulte também</h2> + +<ul> + <li>{{jsxref("Statements/function", "function statement")}}</li> + <li>{{jsxref("Operators/function", "function expression")}}</li> + <li>{{jsxref("Statements/function*", "function* statement")}}</li> + <li>{{jsxref("Operators/function*", "function* expression")}}</li> + <li>{{jsxref("Function")}}</li> + <li>{{jsxref("GeneratorFunction")}}</li> + <li>{{jsxref("Functions/Arrow_functions", "Arrow functions")}}</li> + <li>{{jsxref("Functions/Default_parameters", "Default parameters")}}</li> + <li>{{jsxref("Functions/rest_parameters", "Rest parameters")}}</li> + <li>{{jsxref("Functions/arguments", "Arguments object")}}</li> + <li>{{jsxref("Functions/get", "getter")}}</li> + <li>{{jsxref("Functions/set", "setter")}}</li> + <li>{{jsxref("Functions/Method_definitions", "Method definitions")}}</li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope">Functions and function scope</a></li> +</ul> diff --git a/files/pt-pt/web/javascript/reference/funcoes/parametros_rest/index.html b/files/pt-pt/web/javascript/reference/funcoes/parametros_rest/index.html new file mode 100644 index 0000000000..a21cb25ed6 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/funcoes/parametros_rest/index.html @@ -0,0 +1,234 @@ +--- +title: Parâmetros Rest +slug: Web/JavaScript/Reference/Funcoes/parametros_rest +tags: + - Funcionalidade Linguagem + - Funções + - JavaScript + - Parametros Rest + - Rest +translation_of: Web/JavaScript/Reference/Functions/rest_parameters +--- +<div>Parâmetrois {{jsSidebar("Functions")}}</div> + +<p><span class="seoSummary">A sintaxe do <strong>parâmetro "rest"</strong> permite-nos representar um número indefinido de argumentos</span><span class="seoSummary">como um <em>array</em>.</span></p> + +<div>{{EmbedInteractiveExample("pages/js/functions-restparameters.html")}}</div> + + + +<h2 id="Sintaxe">Sintaxe</h2> + +<pre class="syntaxbox">function f(<var>a</var>, <var>b</var>, ...<var>theArgs</var>) { + // ... +}</pre> + +<h2 id="Descrição">Descrição</h2> + +<p>A function's last parameter can be prefixed with <code>...</code> which will cause all remaining (user supplied) arguments to be placed within a "standard" Javascript array.</p> + +<p>Only the last parameter can be a "rest parameter".</p> + +<pre class="brush: js">function myFun(<var>a</var>, <var>b</var>, ...<var>manyMoreArgs</var>) { + 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] +</pre> + +<h3 id="Difference_between_rest_parameters_and_the_arguments_object">Difference between rest parameters and the <code>arguments</code> object</h3> + +<p>There are three main differences between rest parameters and the {{jsxref("Functions/arguments", "arguments")}} object:</p> + +<ul> + <li>rest parameters are only the ones that haven't been given a separate name (i.e. formally defined in function expression), while the <code>arguments</code> object contains <em>all</em> arguments passed to the function;</li> + <li>the <code>arguments</code> object is not a real array, while rest parameters are {{jsxref("Global_Objects/Array", "Array")}} instances, meaning methods like {{jsxref("Array.sort", "sort")}}, {{jsxref("Array.map", "map")}}, {{jsxref("Array.forEach", "forEach")}} or {{jsxref("Array/pop", "pop")}} can be applied on it directly;</li> + <li>the <code>arguments</code> object has additional functionality specific to itself (like the <code>callee</code> property).</li> +</ul> + +<h3 id="From_arguments_to_an_array">From arguments to an array</h3> + +<p>Rest parameters have been introduced to reduce the boilerplate code that was induced by the arguments</p> + +<pre class="brush: js">// 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 +} +</pre> + +<h3 id="Destructuring_rest_parameters">Destructuring rest parameters</h3> + +<p>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 <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment">Destructuring assignment</a>.)</p> + +<pre class="brush: js">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) +</pre> + +<div class="blockIndicator note"> +<h4 id="Fixme">Fixme</h4> + +<p><s>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.</s> The example is contrived, but imagine that [a, b, c] were the return value of some function. Then the utility is clear.</p> + +<p><s>Also, since <a href="/en-US/docs/Web/JavaScript/Reference/Functions/arguments">Function arguments</a> will never have named parameters (this is not Python), the statement "objects will soon be supported" is wrong. </s> The preceding example may be mixing up destructuring with rest parameters. Please see the <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment">page on destructuring assignment</a> for an example with object destructuring applied in the parameters area.</p> + +<pre class="brush: js">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 ...) +</pre> +</div> + +<h2 id="Exemplos">Exemplos</h2> + +<p>In this example, the first argument is mapped to <code>a</code> and the second to <code>b</code>, so these named arguments are used like normal.</p> + +<p>However, the third argument, <code>manyMoreArgs</code>, will be an array that contains the 3<sup>rd</sup>, 4<sup>th</sup>, 5<sup>th</sup>, 6<sup>th</sup> ... <var>n</var><sup>th</sup> — as many arguments that the user includes.</p> + +<pre class="brush: js">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] +</pre> + +<p>Below... even though there is just one value, the last argument still gets put into an array.</p> + +<pre class="brush: js">// using the same function definition from example above + +myFun("one", "two", "three") + +// a, one +// b, two +// manyMoreArgs, [three]</pre> + +<p>Below, the third argument isn't provided, but <code>manyMoreArgs</code> is still an array (albeit an empty one).</p> + +<pre class="brush: js">// using the same function definition from example above + +myFun("one", "two") + +// a, one +// b, two +// manyMoreArgs, []</pre> + +<p>Since <code>theArgs</code> is an array, a count of its elements is given by the <code>length</code> property:</p> + +<pre class="brush: js">function fun1(...theArgs) { + console.log(theArgs.length) +} + +fun1() // 0 +fun1(5) // 1 +fun1(5, 6, 7) // 3 +</pre> + +<p>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:</p> + +<pre class="brush: js">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] +</pre> + +<p><code>Array</code> methods can be used on rest parameters, but not on the <code>arguments</code> object:</p> + +<pre class="brush: js">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) +</pre> + +<p>To use <code>Array</code> methods on the <code>arguments</code> object, it must be converted to a real array first.</p> + +<pre class="brush: js">function sortArguments() { + let args = Array.from(arguments) + let sortedArgs = args.sort() + return sortedArgs +} +console.log(sortArguments(5, 3, 7, 1)) // 1, 3, 5, 7 +</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificação</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('ESDraft', '#sec-function-definitions', 'Function Definitions')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibildiade_de_navegador">Compatibildiade de navegador</h2> + + + +<p>{{Compat("javascript.functions.rest_parameters")}}</p> + +<h2 id="Consulte_também">Consulte também</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator" title="spread operator">Spread syntax</a> (also ‘<code>...</code>’)</li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Functions/arguments" title="arguments">Arguments object</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" title="Array">Array</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Functions" title="Functions and function scope">Functions</a></li> + <li><a class="external" href="http://wiki.ecmascript.org/doku.php?id=harmony:rest_parameters">Original proposal at ecmascript.org</a></li> + <li><a class="external" href="http://javascriptweblog.wordpress.com/2011/01/18/javascripts-arguments-object-and-beyond/">JavaScript arguments object and beyond</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment">Destructuring assignment</a></li> +</ul> 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 new file mode 100644 index 0000000000..237818a04c --- /dev/null +++ b/files/pt-pt/web/javascript/reference/global_objects/array/concat/index.html @@ -0,0 +1,205 @@ +--- +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 +--- +<div>{{JSRef}}</div> + +<p>O método <code><strong>concat()</strong></code> é usado para concatenar dois ou mais vectores. Este método não altera os vectores existentes, devolvendo ao invés um novo vector.</p> + +<pre class="brush: js">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" ]</pre> + +<h2 id="Sintaxe">Sintaxe</h2> + +<pre class="syntaxbox">var <var>novo_vector</var> = <var>velho_vector</var>.concat(<var>valor1</var>[, <var>valor2</var>[, ...[, <var>valorN</var>]]])</pre> + +<h3 id="Parâmetros">Parâmetros</h3> + +<dl> + <dt><code>valor<em>N</em></code></dt> + <dd>Vectores e/ou valores a concatenar num novo vector. Veja a descrição detalhada abaixo.</dd> +</dl> + +<h3 id="Valor_devolvido">Valor devolvido</h3> + +<p>Uma nova instância de {{jsxref("Array")}}.</p> + +<h2 id="Descrição">Descrição</h2> + +<p>O método <code>concat</code> 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.</p> + +<p>O método <code>concat</code> não altera <code>this</code> 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:</p> + +<ul> + <li>Object references (and not the actual object): <code>concat</code> copies object references into the new array. Both the original and new array refer to the same object. That is, if a referenced object is modified, the changes are visible to both the new and original arrays. This includes elements of array arguments that are also arrays.</li> + <li>Strings, numbers and booleans (not {{jsxref("Global_Objects/String", "String")}}, {{jsxref("Global_Objects/Number", "Number")}}, and {{jsxref("Global_Objects/Boolean", "Boolean")}} objects): <code>concat</code> copies the values of strings and numbers into the new array.</li> +</ul> + +<div class="note"> +<p><strong>Note:</strong> 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.</p> +</div> + +<h2 id="Exemplos">Exemplos</h2> + +<h3 id="Concatenar_dois_vectores">Concatenar dois vectores</h3> + +<p>O código que se segue concatena dois vectores:</p> + +<pre class="brush: js">var alfa = ['a', 'b', 'c']; +var numerico = [1, 2, 3]; + +alfa.concat(numerico); +// resulta em ['a', 'b', 'c', 1, 2, 3] +</pre> + +<h3 id="Concatenar_três_vectores">Concatenar três vectores</h3> + +<p>O código que se segue concatena três vectores:</p> + +<pre class="brush: js">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] +</pre> + +<h3 id="Concatenar_valores_para_um_vector">Concatenar valores para um vector</h3> + +<p>O código que se segue concatena três valores a um vector:</p> + +<pre class="brush: js">var alfa = ['a', 'b', 'c']; + +var alfaNumerico = alfa.concat(1, [2, 3]); + +console.log(alphaNumeric); +// resulta em ['a', 'b', 'c', 1, 2, 3] +</pre> + +<h3 id="Concatenar_vectores_inclusos">Concatenar vectores inclusos</h3> + +<p>O código que se segue concatena vectores inclusos e demonstra retenção de referências:</p> + +<pre class="brush: js">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]] +</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + <tr> + <td>{{SpecName('ES3')}}</td> + <td>{{Spec2('ES3')}}</td> + <td>Definição inicial. Implementado no JavaScript 1.2.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.4.4.4', 'Array.prototype.concat')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-array.prototype.concat', 'Array.prototype.concat')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.concat', 'Array.prototype.concat')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Edge</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Suporte básico</td> + <td>{{CompatChrome("1.0")}}</td> + <td>{{CompatGeckoDesktop("1.7")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatIE("5.5")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Suporte básico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Array.push", "push")}} / {{jsxref("Array.pop", "pop")}} — adicionar/eliminar elementos no fim do vector</li> + <li>{{jsxref("Array.unshift", "unshift")}} / {{jsxref("Array.shift", "shift")}} — adicionar/eliminar elementos no início do vector</li> + <li>{{jsxref("Array.splice", "splice")}} — adicionar e/ou eliminar elementos no local especificado do vector</li> + <li>{{jsxref("String.prototype.concat()")}}</li> + <li>{{jsxref("Symbol.isConcatSpreadable")}} – control flattening.</li> +</ul> 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 new file mode 100644 index 0000000000..3eedeb54a9 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/global_objects/array/find/index.html @@ -0,0 +1,210 @@ +--- +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 +--- +<div>{{JSRef}}</div> + +<p>O método <code><strong>find()</strong></code> retorna o <strong>valor</strong> do primeiro elemento do array que satisfaça a função de teste fornecida. Caso contrário o valor {{jsxref("undefined")}} é retornado.</p> + +<div>{{EmbedInteractiveExample("pages/js/array-find.html")}}</div> + + + +<p>Ver também o método {{jsxref("Array.findIndex", "findIndex()")}} , o qual retorna o <strong>index</strong> de um elemento encontrado num array, em alternativa do seu valor.</p> + +<p>É 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()")}}.</p> + +<h2 id="Sintaxe">Sintaxe</h2> + +<pre class="syntaxbox"><var>arr</var>.find(<var>callback</var>[, <var>thisArg</var>])</pre> + +<h3 id="Parâmetros">Parâmetros</h3> + +<dl> + <dt><code>callback</code></dt> + <dd>Função a executar em cada elemento do array, utilizando três argumentos: + <dl> + <dt><code>element</code></dt> + <dd>O elemento a ser processado no array.</dd> + <dt><code>index</code>{{optional_inline}}</dt> + <dd>O index do elemento a ser processado no array.</dd> + <dt><code>array</code>{{optional_inline}}</dt> + <dd>O array no qual o método <code>find</code> foi chamado.</dd> + </dl> + </dd> + <dt><code>thisArg</code> <code>{{Optional_inline}}</code></dt> + <dd>Objeto para usar como <code>this</code> ao executar a <code>callback</code>.</dd> +</dl> + +<h3 id="Valor_de_retorno">Valor de retorno</h3> + +<p>Um valor do array caso um elemento passe no teste; caso contrário, {{jsxref("undefined")}}.</p> + +<h2 id="Descrição">Descrição</h2> + +<p>O método<code>find</code> executa a <code>callback</code> uma vez para cada index do array até ser encontrado um no qual a <code>callback</code> retorna o valor true. Caso um elemento seja encontrado, o método <code>find</code> retorna imediatamente o seu valor. Caso contrário, o método <code>find</code> retorna {{jsxref("undefined")}}. A função de <code>callback</code> é invocada para cada index do array do <code>0</code> ao <code>length - 1</code> 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.</p> + +<p>A função de <code>callback</code> é invocada com 3 parâmetros: o valor do elemento, o index do elemento, e o Array no qual é executado.</p> + +<p>Se o parâmetro <code>thisArg</code> for disponibilizado ao método <code>find</code>, este será usado como <code>this</code> para cada invocação da <code>callback</code>. Caso contrário, será usado o valor {{jsxref("undefined")}}.</p> + +<p>O método <code>find</code> não altera o array no qual é invocado.</p> + +<p>A quantidade de elementos processados pelo método <code>find</code> é definida antes da invocação da <code>callback</code>. Os elementos adicionados ao array após o método <code>find</code> ter iniciado não serão visitados pela <code>callback</code>. Se um elemento existente e não visitado, for alterado pela <code>callback</code>, o seu valor que foi passado para a <code>callback</code> será o valor a ser avaliado pelo método <code>find</code>; Os elementos eliminados após o inicio do método find também serão visitados.</p> + +<h2 id="Exemplos">Exemplos</h2> + +<h3 id="Encontrar_um_objeto_num_array_através_de_uma_das_suas_propriedades">Encontrar um objeto num array através de uma das suas propriedades</h3> + +<pre class="brush: js">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 }</pre> + +<h3 id="Encontrar_um_número_primo_num_array">Encontrar um número primo num array</h3> + +<p>O seguinte exemplo encontra um elemento no array que seja um número primo (caso não exista, retorna {{jsxref("undefined")}} ).</p> + +<pre class="brush: js">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 +</pre> + +<p>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.</p> + +<pre class="brush: js">// 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); +}); + +</pre> + +<h2 id="Polyfill">Polyfill</h2> + +<p>Este método foi adicionado ao <em>ECMAScript 2015 Language Specification </em>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:</p> + +<pre class="brush: js">// 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; + } + }); +} +</pre> + +<p>É melhor não utilizar o polyfill <code>Array.prototype</code> para motores JavaScript obsoletos que não suportem métodos <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty">Object.defineProperty</a></code>, uma vez que, não é possível torna-los não-enumeráveis.</p> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-array.prototype.find', 'Array.prototype.find')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.find', 'Array.prototype.find')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_de_Browsers">Compatibilidade de Browsers</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Array.find")}}</p> +</div> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li>{{jsxref("Array.prototype.findIndex()")}} – procurar e obter um index</li> + <li>{{jsxref("Array.prototype.includes()")}} – testar se existe um valor num array</li> + <li>{{jsxref("Array.prototype.filter()")}} – encontrar todos os elementos</li> + <li>{{jsxref("Array.prototype.every()")}} – testar se todos os elementos cumprem o requisito</li> +</ul> 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 new file mode 100644 index 0000000000..77e1bcc9d9 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/global_objects/array/foreach/index.html @@ -0,0 +1,328 @@ +--- +title: Array.prototype.forEach() +slug: Web/JavaScript/Reference/Global_Objects/Array/forEach +translation_of: Web/JavaScript/Reference/Global_Objects/Array/forEach +--- +<div>{{JSRef}}</div> + +<p>O método <code><strong>forEach()</strong></code> executa a função que foi fornecida uma vez para cada elemento do vetor (array).</p> + +<div>{{EmbedInteractiveExample("pages/js/array-foreach.html")}}</div> + +<p class="hidden">A origem deste exemplo interactivo está armazenado num repositório do GitHub. Se queres contribuir para o projecto dos exemplos interactivos, por favor clona <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> e manda-nos um pull request.</p> + +<h2 id="Sintaxe">Sintaxe</h2> + +<pre class="syntaxbox"><var>vet</var>.forEach(function <var>callback(presenteValor[, indice[, vetor]]) { + //o teu iterador +}</var>[, <var>argThis</var>]);</pre> + +<h3 id="Parâmetros">Parâmetros</h3> + +<dl> + <dt><code>callback</code></dt> + <dd>Função a executar para cada elemento, levando três argumentos: + <dl> + <dt><code>presenteValor</code></dt> + <dd>Valor do presente elemento a ser processado do vetor (array).</dd> + <dt><code>indice</code>{{optional_inline}}</dt> + <dd>Índice do presente elemento a ser processado do vetor (array).</dd> + <dt><code>vet</code>{{optional_inline}}</dt> + <dd>O vetor (array) a que o <code>forEach()</code> está a ser aplicado.</dd> + </dl> + </dd> + <dt><code>argThis</code> {{Optional_inline}}</dt> + <dd> + <p>Valor a usar como <code><strong>this</strong></code> (ou seja o <code>Object</code> de referência) quando é executado o <code>callback</code>.</p> + </dd> +</dl> + +<h3 id="Valor_devolvido">Valor devolvido</h3> + +<p>{{jsxref("undefined")}}.</p> + +<h2 id="Descrição">Descrição</h2> + +<p><code>forEach()</code> executa o <code>callback</code> 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).</p> + +<p><code>callback</code> é invocado com <strong>três argumentos</strong>:</p> + +<ul> + <li>o <strong>valor do elemento</strong></li> + <li>o <strong>índice do elemento</strong></li> + <li>o <strong>vetor (array) que está a ser percorrido</strong></li> +</ul> + +<p>If a <code>thisArg</code> parameter is provided to <code>forEach()</code>, it will be used as callback's <code>this</code> value. Otherwise, the value {{jsxref("undefined")}} will be used as its <code>this</code> value. The <code>this</code> value ultimately observable by <code>callback</code> is determined according to <a href="/en-US/docs/Web/JavaScript/Reference/Operators/this">the usual rules for determining the <code>this</code> seen by a function</a>.</p> + +<p>The range of elements processed by <code>forEach()</code> is set before the first invocation of <code>callback</code>. Elements that are appended to the array after the call to <code>forEach()</code> begins will not be visited by <code>callback</code>. If the values of existing elements of the array are changed, the value passed to <code>callback</code> will be the value at the time <code>forEach()</code> 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.</p> + +<p><code>forEach()</code> executes the <code>callback</code> 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.</p> + +<p><code>forEach()</code> does not mutate the array on which it is called (although <code>callback</code>, if invoked, may do so).</p> + +<div class="note"> +<p>There is no way to stop or break a <code>forEach()</code> loop other than by throwing an exception. If you need such behavior, the <code>forEach()</code> method is the wrong tool.</p> + +<p>Early termination may be accomplished with:</p> + +<ul> + <li>A simple loop</li> + <li>A <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of">for...of</a> loop</li> + <li>{{jsxref("Array.prototype.every()")}}</li> + <li>{{jsxref("Array.prototype.some()")}}</li> + <li>{{jsxref("Array.prototype.find()")}}</li> + <li>{{jsxref("Array.prototype.findIndex()")}}</li> +</ul> + +<p>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.</p> +</div> + +<h2 id="Examples">Examples</h2> + +<h3 id="Converting_a_for_loop_to_forEach">Converting a for loop to forEach</h3> + +<p>before</p> + +<pre class="brush:js">const items = ['item1', 'item2', 'item3']; +const copy = []; + +for (let i=0; i<items.length; i++) { + copy.push(items[i]) +} +</pre> + +<p>after</p> + +<pre class="brush:js">const items = ['item1', 'item2', 'item3']; +const copy = []; + +items.forEach(function(item){ + copy.push(item) +}); + +</pre> + +<p> </p> + +<h3 id="Printing_the_contents_of_an_Array_Object">Printing the contents of an Array Object</h3> + +<p>The following code logs a line for each element in an array:</p> + +<pre class="brush:js">var userInfo = [{ + name: "Mayank", + age: 30 +}, { + name: Meha, + age: 26 +}]; + +userInfo.forEach(function(employee) { + console.log(employee.name) +}); +</pre> + +<p> </p> + +<p> </p> + +<p> </p> + +<h3 id="Printing_the_contents_of_an_array">Printing the contents of an array</h3> + +<p>The following code logs a line for each element in an array:</p> + +<pre class="brush:js">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 +</pre> + +<h3 id="Using_thisArg">Using <code>thisArg</code></h3> + +<p>The following (contrived) example updates an object's properties from each entry in the array:</p> + +<pre class="brush:js">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 +</pre> + +<p>Since the <code>thisArg</code> parameter (<code>this</code>) is provided to <code>forEach()</code>, it is passed to <code>callback</code> each time it's invoked, for use as its <code>this</code> value.</p> + +<div class="note"> +<p>If passing the function argument using an <a href="/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions">arrow function expression</a> the <code>thisArg</code> parameter can be omitted as arrow functions lexically bind the {{jsxref("Operators/this", "this")}} value.</p> +</div> + +<h3 id="An_object_copy_function">An object copy function</h3> + +<p>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 <code>Array.prototype.forEach()</code> works by using ECMAScript 5 <code>Object.*</code> meta property functions.</p> + +<pre class="brush: js">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 +</pre> + +<h3 id="If_the_array_is_modified_during_iteration_other_elements_might_be_skipped.">If the array is modified during iteration, other elements might be skipped.</h3> + +<p>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. <code>forEach()</code> does not make a copy of the array before iterating.</p> + +<pre class="brush:js">var words = ['one', 'two', 'three', 'four']; +words.forEach(function(word) { + console.log(word); + if (word === 'two') { + words.shift(); + } +}); +// one +// two +// four +</pre> + +<h2 id="Polyfill">Polyfill</h2> + +<p><code>forEach()</code> 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 <code>forEach()</code> 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 <code>callback.call()</code> evaluates to the original value of {{jsxref("Function.prototype.call()")}}.</p> + +<pre class="brush: js">// 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. + }; +} +</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.4.4.18', 'Array.prototype.forEach')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.6.</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-array.prototype.foreach', 'Array.prototype.forEach')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.foreach', 'Array.prototype.forEach')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Array.forEach")}}</p> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Array.prototype.find()")}}</li> + <li>{{jsxref("Array.prototype.findIndex()")}}</li> + <li>{{jsxref("Array.prototype.map()")}}</li> + <li>{{jsxref("Array.prototype.every()")}}</li> + <li>{{jsxref("Array.prototype.some()")}}</li> + <li>{{jsxref("Map.prototype.forEach()")}}</li> + <li>{{jsxref("Set.prototype.forEach()")}}</li> +</ul> 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 new file mode 100644 index 0000000000..201d4c9526 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/global_objects/array/includes/index.html @@ -0,0 +1,175 @@ +--- +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 +--- +<div>{{JSRef}}</div> + +<p>O método <code><strong>includes()</strong></code> determina se um array contém um determinado elemento, devolvendo <code>true</code> ou <code>false</code>. É utilizado o algoritmo sameValueZero para determinar se o elemento especificado foi encontrado.</p> + +<div>{{EmbedInteractiveExample("pages/js/array-includes.html")}}</div> + + + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox"><var>arr</var>.includes(<var>searchElement[</var>, <var>fromIndex]</var>) +</pre> + +<h3 id="Parameters">Parameters</h3> + +<dl> + <dt><code>searchElement</code></dt> + <dd>The element to search for.</dd> + <dt><code>fromIndex</code> {{optional_inline}}</dt> + <dd>The position in this array at which to begin searching for <code>searchElement</code>. A negative value searches from the index of <code>array.length - fromIndex</code> by asc. Defaults to 0.</dd> +</dl> + +<h3 id="Return_value">Return value</h3> + +<p>A {{jsxref("Boolean")}}.</p> + +<h2 id="Examples">Examples</h2> + +<pre class="brush: js">[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 +</pre> + +<h3 id="fromIndex_is_greater_than_or_equal_to_the_array_length"><code>fromIndex</code> is greater than or equal to the array length</h3> + +<p>If <code>fromIndex</code> is greater than or equal to the length of the array, <code>false</code> is returned. The array will not be searched.</p> + +<pre class="brush: js">var arr = ['a', 'b', 'c']; + +arr.includes('c', 3); // false +arr.includes('c', 100); // false</pre> + +<h3 id="Computed_index_is_less_than_0">Computed index is less than 0</h3> + +<p>If <code>fromIndex</code> is negative, the computed index is calculated to be used as a position in the array at which to begin searching for <code>searchElement</code>. If the computed index is less than 0, the entire array will be searched.</p> + +<pre class="brush: js">// 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</pre> + +<h3 id="includes()_used_as_a_generic_method"><code>includes()</code> used as a generic method</h3> + +<p><code>includes()</code> method is intentionally generic. It does not require <code>this</code> 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 <code>includes()</code> method called on the function's <a href="/en-US/docs/Web/JavaScript/Reference/Functions/arguments">arguments</a> object.</p> + +<pre class="brush: js">(function() { + console.log([].includes.call(arguments, 'a')); // true + console.log([].includes.call(arguments, 'd')); // false +})('a','b','c');</pre> + +<h2 id="Polyfill">Polyfill</h2> + +<pre class="brush: js">// 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; + } + }); +} +</pre> + +<p>If you need to support truly obsolete JavaScript engines that don't support <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty">Object.defineProperty</a></code>, it's best not to polyfill <code>Array.prototype</code> methods at all, as you can't make them non-enumerable.</p> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES7', '#sec-array.prototype.includes', 'Array.prototype.includes')}}</td> + <td>{{Spec2('ES7')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.includes', 'Array.prototype.includes')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Array.includes")}}</p> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("TypedArray.prototype.includes()")}}</li> + <li>{{jsxref("String.prototype.includes()")}}</li> + <li>{{jsxref("Array.prototype.indexOf()")}}</li> + <li>{{jsxref("Array.prototype.find()")}}</li> + <li>{{jsxref("Array.prototype.findIndex()")}}</li> +</ul> 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 new file mode 100644 index 0000000000..5f26f41549 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/global_objects/array/index.html @@ -0,0 +1,440 @@ +--- +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 +--- +<div>{{JSRef}}</div> + +<p>A classe de JavaScript <strong><code>Array</code></strong> é um objecto global que é utilizado na construção de matrizes; que são objectos de alto nível, semelhantes a listas.</p> + +<h2 id="Descrição">Descrição</h2> + +<p>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.</p> + +<p>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 à <a href="pt-PT/docs/Web/JavaScript/Estruturas_de_dados#Objetos">coleção de propriedades dessa array</a>. 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.</p> + +<p><strong>Criar uma Array</strong></p> + +<pre class="brush: js notranslate">var fruits = ['Apple', 'Banana']; + +console.log(fruits.length); +// 2 +</pre> + +<p><strong>Aceder (através de índice) item<span class="original-content"> da </span>Array</strong></p> + +<pre class="brush: js notranslate">var first = fruits[0]; +// Apple + +var last = fruits[fruits.length - 1]; +// Banana +</pre> + +<p><strong>Loop over an Array</strong></p> + +<pre class="brush: js notranslate">fruits.forEach(function(item, index, array) { + console.log(item, index); +}); +// Apple 0 +// Banana 1 +</pre> + +<p><strong>Adicionar um item ao fim da Array</strong></p> + +<pre class="brush: js notranslate">var newLength = fruits.push('Orange'); +// ["Apple", "Banana", "Orange"] +</pre> + +<p><strong>Remover um item do fim da Array</strong></p> + +<pre class="brush: js notranslate">var last = fruits.pop(); // remove Orange (from the end) +// ["Apple", "Banana"]; +</pre> + +<p><strong>Remover um item do início da Array</strong></p> + +<pre class="brush: js notranslate">var first = fruits.shift(); // remove Apple from the front +// ["Banana"]; +</pre> + +<p><strong>Ad</strong><strong>icionar um item ao início da Array</strong></p> + +<pre class="brush: js notranslate">var newLength = fruits.unshift('Strawberry') // add to the front +// ["Strawberry", "Banana"]; +</pre> + +<p><strong>Encontrar o índice dum item na Array</strong></p> + +<pre class="brush: js notranslate">fruits.push('Mango'); +// ["Strawberry", "Banana", "Mango"] + +var pos = fruits.indexOf('Banana'); +// 1 +</pre> + +<p><strong>Remover um item pela posição do índice</strong></p> + +<pre class="brush: js notranslate">var removedItem = fruits.splice(pos, 1); // this is how to remove an item + +// ["Strawberry", "Mango"]</pre> + +<p><strong>Remover items pela posição do índice</strong></p> + +<pre class="brush: js notranslate">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"]</pre> + +<p><strong>Copiar uma Array</strong></p> + +<pre class="brush: js notranslate">var shallowCopy = fruits.slice(); // this is how to make a copy +// ["Strawberry"] +</pre> + +<h3 id="Como_aceder_a_elementos_da_array">Como aceder a elementos da array</h3> + +<p>JavaScript arrays are zero-indexed: the first element of an array is at index <code>0</code>, and the last element is at the index equal to the value of the array's {{jsxref("Array.length", "length")}} property minus 1.</p> + +<pre class="brush: js notranslate">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' +</pre> + +<p>Array elements are object properties in the same way that <code>toString</code> 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:</p> + +<pre class="brush: js notranslate">console.log(arr.0); // a syntax error +</pre> + +<p>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 <code>'3d'</code>, it can only be referenced using bracket notation. E.g.:</p> + +<pre class="brush: js notranslate">var years = [1950, 1960, 1970, 1980, 1990, 2000, 2010]; +console.log(years.0); // a syntax error +console.log(years[0]); // works properly +</pre> + +<pre class="brush: js notranslate">renderer.3d.setTexture(model, 'character.png'); // a syntax error +renderer['3d'].setTexture(model, 'character.png'); // works properly +</pre> + +<p>Note that in the <code>3d</code> example, <code>'3d'</code> had to be quoted. It's possible to quote the JavaScript array indexes as well (e.g., <code>years['2']</code> instead of <code>years[2]</code>), although it's not necessary. The 2 in <code>years[2]</code> is coerced into a string by the JavaScript engine through an implicit <code>toString</code> conversion. It is for this reason that <code>'2'</code> and <code>'02'</code> would refer to two different slots on the <code>years</code> object and the following example could be <code>true</code>:</p> + +<pre class="brush: js notranslate">console.log(years['2'] != years['02']); +</pre> + +<p>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):</p> + +<pre class="brush: js notranslate">var promise = { + 'var' : 'text', + 'array': [1, 2, 3, 4] +}; + +console.log(promise['var']); +</pre> + +<h3 id="Relationship_between_length_and_numerical_properties">Relationship between <code>length</code> and numerical properties</h3> + +<p>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.</p> + +<pre class="brush: js notranslate">var fruits = []; +fruits.push('banana', 'apple', 'peach'); + +console.log(fruits.length); // 3 +</pre> + +<p>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:</p> + +<pre class="brush: js notranslate">fruits[5] = 'mango'; +console.log(fruits[5]); // 'mango' +console.log(Object.keys(fruits)); // ['0', '1', '2', '5'] +console.log(fruits.length); // 6 +</pre> + +<p>Increasing the {{jsxref("Array.length", "length")}}.</p> + +<pre class="brush: js notranslate">fruits.length = 10; +console.log(Object.keys(fruits)); // ['0', '1', '2', '5'] +console.log(fruits.length); // 10 +</pre> + +<p>Decreasing the {{jsxref("Array.length", "length")}} property does, however, delete elements.</p> + +<pre class="brush: js notranslate">fruits.length = 2; +console.log(Object.keys(fruits)); // ['0', '1'] +console.log(fruits.length); // 2 +</pre> + +<p>This is explained further on the {{jsxref("Array.length")}} page.</p> + +<h3 id="Creating_an_array_using_the_result_of_a_match">Creating an array using the result of a match</h3> + +<p>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:</p> + +<pre class="brush: js notranslate">// 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'); +</pre> + +<p>The properties and elements returned from this match are as follows:</p> + +<table class="fullwidth-table"> + <tbody> + <tr> + <td class="header">Property/Element</td> + <td class="header">Description</td> + <td class="header">Example</td> + </tr> + <tr> + <td><code>input</code></td> + <td>A read-only property that reflects the original string against which the regular expression was matched.</td> + <td>cdbBdbsbz</td> + </tr> + <tr> + <td><code>index</code></td> + <td>A read-only property that is the zero-based index of the match in the string.</td> + <td>1</td> + </tr> + <tr> + <td><code>[0]</code></td> + <td>A read-only element that specifies the last matched characters.</td> + <td>dbBd</td> + </tr> + <tr> + <td><code>[1], ...[n]</code></td> + <td>Read-only elements that specify the parenthesized substring matches, if included in the regular expression. The number of possible parenthesized substrings is unlimited.</td> + <td>[1]: bB<br> + [2]: d</td> + </tr> + </tbody> +</table> + +<h2 id="Properties">Properties</h2> + +<dl> + <dt><code>Array.length</code></dt> + <dd>The <code>Array</code> constructor's length property whose value is 1.</dd> + <dt>{{jsxref("Array.@@species", "get Array[@@species]")}}</dt> + <dd>The constructor function that is used to create derived objects.</dd> + <dt>{{jsxref("Array.prototype")}}</dt> + <dd>Allows the addition of properties to all array objects.</dd> +</dl> + +<h2 id="Methods">Methods</h2> + +<dl> + <dt>{{jsxref("Array.from()")}}</dt> + <dd>Creates a new <code>Array</code> instance from an array-like or iterable object.</dd> + <dt>{{jsxref("Array.isArray()")}}</dt> + <dd>Returns true if a variable is an array, if not false.</dd> + <dt>{{jsxref("Array.of()")}}</dt> + <dd>Creates a new <code>Array</code> instance with a variable number of arguments, regardless of number or type of the arguments.</dd> +</dl> + +<h2 id="Array_instances"><code>Array</code> instances</h2> + +<p>All <code>Array</code> instances inherit from {{jsxref("Array.prototype")}}. The prototype object of the <code>Array</code> constructor can be modified to affect all <code>Array</code> instances.</p> + +<h3 id="Properties_2">Properties</h3> + +<div>{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype', 'Properties')}}</div> + +<h3 id="Methods_2">Methods</h3> + +<h4 id="Mutator_methods">Mutator methods</h4> + +<div>{{page('en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype', 'Mutator_methods')}}</div> + +<h4 id="Accessor_methods">Accessor methods</h4> + +<div>{{page('en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype', 'Accessor_methods')}}</div> + +<h4 id="Iteration_methods">Iteration methods</h4> + +<div>{{page('en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype', 'Iteration_methods')}}</div> + +<h2 id="Array_generic_methods"><code>Array</code> generic methods</h2> + +<div class="warning"> +<p><strong>Array generics are non-standard, deprecated and will get removed in the near future</strong>. </p> +</div> + +<p>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 <var>str</var> is a letter, you would write:</p> + +<pre class="brush: js notranslate">function isLetter(character) { + return character >= 'a' && character <= 'z'; +} + +if (Array.prototype.every.call(str, isLetter)) { + console.log("The string '" + str + "' contains only letters!"); +} +</pre> + +<p>This notation is rather wasteful and JavaScript 1.6 introduced a generic shorthand:</p> + +<pre class="brush: js notranslate">if (Array.every(str, isLetter)) { + console.log("The string '" + str + "' contains only letters!"); +} +</pre> + +<p>{{jsxref("Global_Objects/String", "Generics", "#String_generic_methods", 1)}} are also available on {{jsxref("String")}}.</p> + +<p>These are <strong>not</strong> 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:</p> + +<pre class="brush: js notranslate">if (Array.from(str).every(isLetter)) { + console.log("The string '" + str + "' contains only letters!"); +} +</pre> + +<h2 id="Examples">Examples</h2> + +<h3 id="Creating_an_array">Creating an array</h3> + +<p>The following example creates an array, <code>msgArray</code>, with a length of 0, then assigns values to <code>msgArray[0]</code> and <code>msgArray[99]</code>, changing the length of the array to 100.</p> + +<pre class="brush: js notranslate">var msgArray = []; +msgArray[0] = 'Hello'; +msgArray[99] = 'world'; + +if (msgArray.length === 100) { + console.log('The length is 100.'); +} +</pre> + +<h3 id="Creating_a_two-dimensional_array">Creating a two-dimensional array</h3> + +<p>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.</p> + +<pre class="brush: js notranslate">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')); +</pre> + +<p>Here is the output:</p> + +<pre class="eval notranslate">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 +</pre> + +<h3 id="Using_an_array_to_tabulate_a_set_of_values">Using an array to tabulate a set of values</h3> + +<pre class="brush: js notranslate">values = []; +for (var x = 0; x < 10; x++){ + values.push([ + 2 ** x, + 2 * x ** 2 + ]) +}; +console.table(values)</pre> + +<p>Results in</p> + +<pre class="eval notranslate">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</pre> + +<p>(First column is the (index))</p> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.4', 'Array')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>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")}}</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-array-objects', 'Array')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>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")}}</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array-objects', 'Array')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td>New method added: {{jsxref("Array.prototype.includes()")}}</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_de_Navegadores">Compatibilidade de Navegadores</h2> + +<div class="hidden">A tabela de compatibilidade nesta página é gerada a partir de dados estruturados. Se quiser contribuir para os dados, por favor consulte <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> e envie-nos um pull request.</div> + +<p>{{Compat("javascript.builtins.Array")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#Indexing_object_properties">JavaScript Guide: “Indexing object properties”</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Guide/Predefined_Core_Objects#Array_Object">JavaScript Guide: “Predefined Core Objects: <code>Array</code> Object”</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Array_comprehensions">Array comprehensions</a></li> + <li><a href="https://github.com/plusdude/array-generics">Polyfill for JavaScript 1.8.5 Array Generics and ECMAScript 5 Array Extras</a></li> + <li><a href="/en-US/docs/JavaScript_typed_arrays">Typed Arrays</a></li> +</ul> 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 new file mode 100644 index 0000000000..aec6f34cc2 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/global_objects/array/join/index.html @@ -0,0 +1,90 @@ +--- +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 +--- +<div>{{JSRef}}</div> + +<p>O método <code><strong>join()</strong></code> cria e devolve uma <em>string</em> ao concatenar todos os elementos numa <em>array</em> (ou <a href="/en-US/docs/Web/JavaScript/Guide/Indexed_collections#Working_with_array-like_objects">objeto como um vetor / matriz</a>) numa cadeia separada por vírgulas ou outro separador especificado. Se a <em>array</em> tem um só item, esse item é devolvido sem o uso do separador.</p> + +<div>{{EmbedInteractiveExample("pages/js/array-join.html")}}</div> + + + +<h2 id="Sintaxe">Sintaxe</h2> + +<pre class="syntaxbox notranslate"><var>vec</var>.join([<var>separador</var>])</pre> + +<h3 id="Parâmetros">Parâmetros</h3> + +<dl> + <dt><code>separador</code> {{optional_inline}}</dt> + <dd>Especifica uma <em>string</em> (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 <code>separador</code> é uma cadeia vazia, todos os elementos são unidos sem qualquer caráter entre eles.</dd> +</dl> + +<h3 id="Resultado">Resultado</h3> + +<p>Uma cadeia (de caracteres) com todos os elementos do vetor unidos. Se <code><em>vec</em>.length</code> é <code>0</code>, é devolvida uma cadeia vazia.</p> + +<h2 id="Descrição">Descrição</h2> + +<p>As conversões de todos os elementos do vetor para cadeias (de caracteres) são unidas numa única cadeia.</p> + +<p>Caso algum elemento seja <code>undefined</code>, <code>null</code> ou um vetor vazio <code>[]</code>, este será convertido numa cadeia vazia.</p> + +<h2 id="Exemplos">Exemplos</h2> + +<h3 id="Juntar_um_vetor_de_quatro_formas_diferentes">Juntar um vetor de quatro formas diferentes</h3> + +<p>O exemplo que se segue cria um vetor, <code>a</code>, 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.</p> + +<pre class="brush: js notranslate">var a = ['Vento', 'Chuva', 'Fogo']; +a.join(); // 'Vento,Chuva,Fogo' +a.join(', '); // 'Vento, Chuva, Fogo' +a.join(' + '); // 'Vento + Chuva + Fogo' +a.join(''); // 'VentoChuvaFogo'</pre> + +<h3 id="Juntar_um_objeto_como_vetor">Juntar um objeto como vetor</h3> + +<p>O seguinte exemplo junta um objeto como vetor (<code><a href="https://wiki.developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments">arguments</a></code>), ao chamar {{jsxref("Function.prototype.call")}} no <code>Array.prototype.join</code>.</p> + +<pre class="brush: js notranslate">function f(a, b, c) { + var s = Array.prototype.join.call(arguments); + console.log(s); // '<span class="message-body-wrapper"><span class="message-flex-body"><span class="devtools-monospace message-body"><span class="objectBox objectBox-string">1,a,true'</span></span></span></span> +} +f(1, 'a', true); +// valor devolvido: "1,a,true" +</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificação</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.join', 'Array.prototype.join')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade">Compatibilidade</h2> + + + +<p>{{Compat("javascript.builtins.Array.join")}}</p> + +<h2 id="Veja_também">Veja também</h2> + +<ul> + <li>{{jsxref("String.prototype.split()")}}</li> + <li>{{jsxref("Array.prototype.toString()")}}</li> + <li>{{jsxref("TypedArray.prototype.join()")}}</li> +</ul> 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 new file mode 100644 index 0000000000..12910ebc2a --- /dev/null +++ b/files/pt-pt/web/javascript/reference/global_objects/array/map/index.html @@ -0,0 +1,366 @@ +--- +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 +--- +<div>{{JSRef}}</div> + +<p><span class="seoSummary">O método <code><strong>map()</strong></code> <strong>cria uma nova array</strong> preenchida com os resultados da chamada de uma função fornecida em cada elemento da matriz de chamada.</span></p> + +<div>{{EmbedInteractiveExample("pages/js/array-map.html")}}</div> + +<div class="hidden">The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> and send us a pull request.</div> + +<h2 id="Sintaxe">Sintaxe</h2> + +<pre class="syntaxbox notranslate">let <var>new_array</var> = <var>arr</var>.map(function <var>callback</var>( <var>currentValue</var>[, <var>index</var>[, <var>array</var>]]) { + // retorna novo elemento para new_array +}[, <var>thisArg</var>]) +</pre> + +<h3 id="Parameteros">Parameteros</h3> + +<dl> + <dt><code><var>callback</var></code></dt> + <dd> + <p>Função que é chamada para cada elemento de <code>arr</code>. Cada vez que a função <code>callback</code> é executada, o valor devolvido é acrescentado a <code>new_array</code>.</p> + + <p>A função <code><var>callback</var></code> aceita os seguintes argumentos:</p> + + <dl> + <dt><code><var>currentValue</var></code></dt> + <dd>O elemento da matriz a ser processado.</dd> + <dt><code><var>index</var></code>{{optional_inline}}</dt> + <dd>O indice do elemento da matriz a ser processado.</dd> + <dt><code><var>array</var></code>{{optional_inline}}</dt> + <dd>A matriz em que a função <code>map</code> foi chamada.</dd> + </dl> + </dd> + <dt><code>thisArg</code>{{optional_inline}}</dt> + <dd>Valor para usar como <code>this</code> ao executar a função <code><var>callback</var></code>.</dd> +</dl> + +<h3 id="Valor_de_retorno">Valor de retorno</h3> + +<p>Uma nova matriz em que cada elemento é um resultado da função callback..</p> + +<h2 id="Descrição">Descrição</h2> + +<p><code>map</code> chama a função <code><var>callback</var></code> <strong>uma vez por cada elemento</strong> na matriz, por ordem, e cria uma matriz com os resultados. <code><var>callback</var></code> é só chamada nos indices da matriz que têm valores (inclusive {{jsxref("undefined")}}).</p> + +<p>Não é chamada para elementos que não pertecem à matriz; isto sendo:</p> + +<ul> + <li>indices que não pertencem pela matriz;</li> + <li>que foram eliminados; ou</li> + <li>que nunca tiveram um valor.</li> +</ul> + +<h3 id="Quando_não_usar_map">Quando não usar map()</h3> + +<p>Como <code>map</code> map cira uma nova matriz, é um <em>anti-pattern</em> 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")}}.</p> + +<p>Não deve usar <code>map</code> se:</p> + +<ul> + <li>não vai usar o valor devolvido; e/ou</li> + <li>o <code>callback</code> não devolve um valor.</li> +</ul> + +<h3 id="Parameteros_em_detalhe">Parameteros em detalhe</h3> + +<p><code><var>callback</var></code> é chamada com três argumentos: o valor do elemento, o indice do elemento, e a matriz do objeto a ser mapeado.</p> + +<p>Se o parametero <code>thisArg</code> é fornecido, é usado como o valor de <code>this</code> na função <em><code>callback</code></em>. Se não, o valor {{jsxref("undefined")}} é usado como o valor de <code>this</code>. O valor de <code>this</code> no corpo da função <code><var>callback</var></code> é determinado de acordo com <a href="/en-US/docs/Web/JavaScript/Reference/Operators/this">as regras habituais para determinar o valor de this numa função</a>.</p> + +<p><code>map</code> não modifica a matriz em que é chamada (embora a função <em><code>callback</code></em>, se invocada, possa fazê-lo).</p> + +<p>A série de elementos processados por <code>map</code> é definida antes da primeira invocação de <em><code>callback</code></em>. Os elementos que são anexados ao conjunto após a chamada para <code>map</code> não serão visitados por <code><em>callback</em></code>. Se os elementos existentes da matriz forem alterados, o seu valor como passado para <em><code>callback</code></em> será o valor no momento em que <code>map</code> os visitar. Os elementos que são apagados após a chamada para <code>map</code> começa e antes de serem visitados, não são visitados.</p> + +<p>Devido ao algoritmo defenido na especificação, se a matriz em que <code>map</code> é chamada for esparsa, a matriz resultante também o será com os mesmos indices em branco.</p> + +<h2 id="Polyfill">Polyfill</h2> + +<p><code>map</code> was added to the ECMA-262 standard in the 5th edition. Therefore, it may not be present in all implementations of the standard.</p> + +<p>You can work around this by inserting the following code at the beginning of your scripts, allowing use of <code>map</code> 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 <code>callback.call</code> evaluates to the original value of <code>{{jsxref("Function.prototype.call")}}</code>.</p> + +<pre class="brush: js notranslate">// 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; + }; +} +</pre> + +<h2 id="Examples">Examples</h2> + +<h3 id="Mapping_an_array_of_numbers_to_an_array_of_square_roots">Mapping an array of numbers to an array of square roots</h3> + +<p>The following code takes an array of numbers and creates a new array containing the square roots of the numbers in the first array.</p> + +<pre class="brush: js notranslate">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] +</pre> + +<h3 id="Using_map_to_reformat_objects_in_an_array">Using map to reformat objects in an array</h3> + +<p>The following code takes an array of objects and creates a new array containing the newly reformatted objects.</p> + +<pre class="brush: js notranslate">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}] +</pre> + +<h3 id="Mapping_an_array_of_numbers_using_a_function_containing_an_argument">Mapping an array of numbers using a function containing an argument</h3> + +<p>The following code shows how <code>map</code> works when a function requiring one argument is used with it. The argument will automatically be assigned from each element of the array as <code>map</code> loops through the original array.</p> + +<pre class="brush: js notranslate">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] +</pre> + +<h3 id="Using_map_generically">Using map generically</h3> + +<p>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:</p> + +<pre class="brush: js notranslate">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] +</pre> + +<h3 id="Using_map_generically_querySelectorAll">Using map generically querySelectorAll</h3> + +<p>This example shows how to iterate through a collection of objects collected by <code>querySelectorAll</code>. This is because <code>querySelectorAll</code> returns a <code>NodeList</code> (which is a collection of objects).</p> + +<p>In this case, we return all the selected <code>option</code>s' values on the screen:</p> + +<pre class="brush: js notranslate">let elems = document.querySelectorAll('select option:checked') +let values = Array.prototype.map.call(elems, function(obj) { + return obj.value +}) +</pre> + +<p>An easier way would be the {{jsxref("Array.from()")}} method.</p> + +<h3 id="Tricky_use_case">Tricky use case</h3> + +<p>(<a href="http://www.wirfs-brock.com/allen/posts/166">inspired by this blog post</a>)</p> + +<p>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.</p> + +<p>Consider:</p> + +<pre class="brush: js notranslate">["1", "2", "3"].map(parseInt)</pre> + +<p>While one might expect <code>[1, 2, 3]</code>, the actual result is <code>[1, NaN, NaN]</code>.</p> + +<p>{{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, <code>Array.prototype.map</code> passes 3 arguments:</p> + +<ul> + <li>the element</li> + <li>the index</li> + <li>the array</li> +</ul> + +<p>The third argument is ignored by {{jsxref("parseInt")}}—but <em>not</em> the second one! This is the source of possible confusion.</p> + +<p>Here is a concise example of the iteration steps:</p> + +<pre class="brush: js notranslate">// 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 +</pre> + +<p>Then let's talk about solutions.</p> + +<pre class="brush: js notranslate">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] +</pre> + +<p>One alternative output of the map method being called with {{jsxref("parseInt")}} as a parameter runs as follows:</p> + +<pre class="brush: js notranslate">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.</pre> + +<h3 id="Mapped_array_contains_undefined">Mapped array contains undefined</h3> + +<p>When {{jsxref("undefined")}} or nothing is returned:</p> + +<pre class="brush: js notranslate">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] + +</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificação</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.map', 'Array.prototype.map')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade">Compatibilidade</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Array.map")}}</p> +</div> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li>{{jsxref("Array.prototype.forEach()")}}</li> + <li>{{jsxref("Map")}} object</li> + <li>{{jsxref("Array.from()")}}</li> +</ul> 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 new file mode 100644 index 0000000000..440ea3e6ee --- /dev/null +++ b/files/pt-pt/web/javascript/reference/global_objects/array/pop/index.html @@ -0,0 +1,96 @@ +--- +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 +--- +<div>{{JSRef}}</div> + +<p>O método <code><strong>pop()</strong></code> remove o último elemento de um array e retorna esse elemento. Este método altera o tamanho do array.</p> + +<div>{{EmbedInteractiveExample("pages/js/array-pop.html")}}</div> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox"><var>arr</var>.pop()</pre> + +<h3 id="Valor_retornado">Valor retornado</h3> + +<p>O elemento removido do array; {{jsxref("undefined")}} se o array estiver vazio.</p> + +<h2 id="Descrição">Descrição</h2> + +<p>O método <code>pop</code> remove o último elemento de um array e retorna esse elemento para a função que o chamou.</p> + +<p><code>pop</code> é 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 <code>length</code> (tamanho) que reflete o último elemento numa lista de consecutivas propriedades numéricas zero-based, pode não se comportar de maneira significativa.</p> + +<p><code><font face="Open Sans, arial, x-locale-body, sans-serif"><span style="background-color: #ffffff;">Se o método </span></font>pop()</code> for chamado num array vazio este retorna {{jsxref("undefined")}}.</p> + +<h2 id="Exemplos">Exemplos</h2> + +<h3 id="Remover_o_último_elemento_de_um_array">Remover o último elemento de um array</h3> + +<p>O seguinte exemplo cria um array <font face="consolas, Liberation Mono, courier, monospace"><span style="background-color: rgba(220, 220, 220, 0.5);">peixes</span></font> que contêm quatro elementos, e depois remove o último elemento.</p> + +<pre class="brush: js">var peixes = ['anjo', 'palhaço', 'mandarim', 'esturjão']; + +var popped = peixes.pop(); + +console.log(peixes); // ['anjo', 'palhaço', 'mandarim'] + +console.log(popped); // 'esturjão'</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES3')}}</td> + <td>{{Spec2('ES3')}}</td> + <td>Definição inicial. Implementada no JavaScript 1.2.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.4.4.6', 'Array.prototype.pop')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-array.prototype.pop', 'Array.prototype.pop')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.pop', 'Array.prototype.pop')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade">Compatibilidade</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Array.pop")}}</p> +</div> + +<h2 id="Ver_também">Ver também </h2> + +<ul> + <li>{{jsxref("Array.prototype.push()")}}</li> + <li>{{jsxref("Array.prototype.shift()")}}</li> + <li>{{jsxref("Array.prototype.unshift()")}}</li> + <li>{{jsxref("Array.prototype.concat()")}}</li> + <li>{{jsxref("Array.prototype.splice()")}}</li> +</ul> 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 new file mode 100644 index 0000000000..a442018c61 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/global_objects/array/reverse/index.html @@ -0,0 +1,133 @@ +--- +title: Array.prototype.reverse() +slug: Web/JavaScript/Reference/Global_Objects/Array/reverse +translation_of: Web/JavaScript/Reference/Global_Objects/Array/reverse +--- +<div>{{JSRef}}</div> + +<p>O método <code><strong>reverse()</strong></code> inverte um vector (<code>Array</code>). O primeiro elemento torna-se o último, e o último elemento torna-se o primeiro.</p> + +<pre class="brush: js">var a = ['um', 'dois', 'três']; +a.reverse(); + +console.log(a); // ['três', 'dois', 'um'] +</pre> + +<h2 id="Sintaxe">Sintaxe</h2> + +<pre class="syntaxbox"><var>a</var>.reverse()</pre> + +<h3 id="Valor_devolvido">Valor devolvido</h3> + +<p>O vector (<code>Array</code>) invertido.</p> + +<h2 id="Descrição">Descrição</h2> + +<p>O método <code>reverse</code> transpõe os elementos do vector que o chamou, mudando o vector, e devolvendo uma referência para o vector.</p> + +<h2 id="Exemplos">Exemplos</h2> + +<h3 id="Invertendo_os_elementos_num_vector">Invertendo os elementos num vector</h3> + +<p>O exemplo que se segue cria um vector <code>a</code>, que contém três elementos, e depois o inverte. A chamada a <code>reverse()</code> devolve uma referência para o vector invertido <code>a</code>.</p> + +<pre class="brush: js">var a = ['um', 'dois', 'três']; +var invertido = a.reverse(); + +console.log(a); // ['três', 'dois', 'um'] +console.log(invertido); // ['três', 'dois', 'um'] +</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.1.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.4.4.8', 'Array.prototype.reverse')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-array.prototype.reverse', 'Array.prototype.reverse')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.reverse', 'Array.prototype.reverse')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Edge</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatChrome("1.0")}}</td> + <td>{{CompatGeckoDesktop("1.7")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatIE("5.5")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Array.prototype.join()")}}</li> + <li>{{jsxref("Array.prototype.sort()")}}</li> + <li>{{jsxref("TypedArray.prototype.reverse()")}}</li> +</ul> 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 new file mode 100644 index 0000000000..48820a1ff7 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/global_objects/array/slice/index.html @@ -0,0 +1,154 @@ +--- +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 +--- +<div>{{JSRef}}</div> + +<p>O método <code><strong>slice()</strong></code> devolve uma cópia rasa (é feita uma cópia dos <em>pointers</em> se for um objeto) de uma parte de uma matriz num novo objeto de <code>array</code> selecionado do <code>start</code> (início incluído) ao <code>end</code> (fim excluído) onde o <code>start</code> e o <code>end</code> representam o índice de itens dessa matriz. A matriz original não é modificada.</p> + +<div>{{EmbedInteractiveExample("pages/js/array-slice.html")}}</div> + +<p class="hidden">The source for this interactive demo is stored in a GitHub repository. If you'd like to contribute to the interactive demo project, please clone <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> and send us a pull request.</p> + +<h2 id="Sintaxe">Sintaxe</h2> + +<pre class="syntaxbox notranslate"><var>arr</var>.slice([<var>start</var>[, <var>end</var>]]) +</pre> + +<h3 id="Parâmetros">Parâmetros</h3> + +<dl> + <dt><code><var>start</var></code> {{optional_inline}}</dt> + <dd>Indice de base zero, onde coméça a cópia.</dd> + <dd>Um índice negativo pode ser utilizado, indicando um intervalo a partir do fim da sequência. <code>slice(-2)</code> extrai os dois últimos elementos da sequência.</dd> + <dd>Se <code><var>start</var></code> é undefined, <code>slice</code> coméça a partir do indice <code>0</code>.</dd> + <dd>Se <code><var>start</var></code> é maior que o último índice da sequência, uma matriz vazia é devolvida.</dd> + <dt><code><var>end</var></code> {{optional_inline}}</dt> + <dd>Índice antes do qual se deve terminar a extração. <code>slice</code> extrai até o valor de indice <code>end</code>, mas sem incluir <code>end</code>. Por exemplo, <code>slice(1,4)</code> extrai do segundo até ao quarto elemento (elementos indexados 1, 2, e 3).</dd> + <dd>Pode ser utilizado um índice negativo, indicando o último índice a partir do fim da sequência. <code>slice(2,-1)</code> extrai do terceiro até ao penúltimo elemento na sequência.</dd> + <dd>Se <code>end</code> é omisso, <code>slice</code> extrai todos os elementos até ao fim da sequência (<code>arr.length</code>).</dd> + <dd>Se <code>end</code> é maior que o comprimento da sequência, <code>slice</code> extrai todos os elementos até ao fim da sequência (<code>arr.length</code>).</dd> +</dl> + +<h3 id="Resultado">Resultado</h3> + +<p>Uma matriz nova contendo os elementos extraídos.</p> + +<h2 id="Descrição">Descrição</h2> + +<p><code>slice</code> 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:</p> + +<ul> + <li>Para referências de objectos (e não o objecto real), <code>slice</code> copia as referências de objectos para a nova matriz. Tanto o original como a nova matriz referem-se ao mesmo objecto. Se um objecto referenciado mudar, as mudanças são visíveis tanto para a nova matriz como para a original.</li> + <li>Para strings, números e booleanos (não {{jsxref("String")}}, {{jsxref("Number")}} e {{jsxref("Booleano")}} objetos), <code>slice</code> copia os valores para a nova matriz. Alterações à string, número, ou booleano numa matriz não afetam a outra matriz.</li> +</ul> + +<p>Se um novo elemento é adicionado a qualquer das matrizes, a outra matriz não é afetada.</p> + +<h2 id="Exemplos">Exemplos</h2> + +<h3 id="Devolver_uma_porção_duma_matriz">Devolver uma porção duma matriz</h3> + +<pre class="brush: js notranslate">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'] +</pre> + +<h3 id="Usar_slice">Usar <code>slice</code></h3> + +<p>No seguinte exemplo, <code>slice</code> cria uma <em>array</em> (matriz), <code>newCar</code>, a partir de <code>myCar</code>. Ambos incluem uma referência ao objeto <code>myHonda</code>. Quando a propriedade <em>color</em> (cor) de <code>myHonda</code> é mudada para <em>purple</em> (roxo), ambas matrizes refletem a alteração.</p> + +<pre class="brush: js notranslate">// 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) +</pre> + +<p>Este <em>script</em> imprime:</p> + +<pre class="notranslate">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 +</pre> + +<h3 id="Objetos_parecidos_com_Array">Objetos parecidos com Array</h3> + +<p>O método <code>slice</code> tembém pode ser chamado para converter objetos / coleções do estilo matriz para um objeto <code>Array</code>. É só preciso {{jsxref("Function.prototype.bind", "<em>bind</em>")}} o método ao objeto. Os {{jsxref("Functions/arguments", "argumentos")}} dentro da função são um exemplo de um "objeto de estilo matriz".</p> + +<pre class="brush: js notranslate">function list() { + return Array.prototype.slice.call(arguments) +} + +let list1 = list(1, 2, 3) // [1, 2, 3] +</pre> + +<p><em>Binding</em> pode ser feito com o método {{jsxref("Function.prototype.call", "call()")}} de {{jsxref("Function.prototype")}} e também pode ser simplificado a usar <code>[].slice.call(arguments)</code> invés de <code>Array.prototype.slice.call</code>.</p> + +<p>Pode ser simplificado a usar {{jsxref("Function.prototype.bind", "bind")}}.</p> + +<pre class="brush: js notranslate">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]</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificação</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.slice', 'Array.prototype.slice')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade">Compatibilidade</h2> + + + +<p>{{Compat("javascript.builtins.Array.slice")}}</p> + +<h2 id="Veja_também">Veja também</h2> + +<ul> + <li>{{jsxref("Array.prototype.splice()")}}</li> + <li>{{jsxref("Function.prototype.call()")}}</li> + <li>{{jsxref("Function.prototype.bind()")}}</li> +</ul> 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 new file mode 100644 index 0000000000..c612f44b26 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/global_objects/arraybuffer/index.html @@ -0,0 +1,219 @@ +--- +title: ArrayBuffer +slug: Web/JavaScript/Reference/Global_Objects/ArrayBuffer +translation_of: Web/JavaScript/Reference/Global_Objects/ArrayBuffer +--- +<div>{{JSRef}}</div> + +<div><strong><code>ArrayBuffer </code></strong>é 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 <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray">typed array objects</a> ou um objeto {{jsxref("DataView")}} que representa um buffer num formato especifico, e usa-o para ler e escrever o conteudo do buffer. </div> + +<div> </div> + +<h2 id="Sintaxe">Sintaxe</h2> + +<pre class="syntaxbox">new ArrayBuffer(length) +</pre> + +<h3 id="Parametros">Parametros</h3> + +<dl> + <dt><code>length</code></dt> + <dd>O tamanho, em bytes, do array buffer que se pretende criar.</dd> +</dl> + +<h3 id="Retorno">Retorno</h3> + +<p> Um novo objecto do tipo <code>ArrayBuffer</code> do tamanho especificado. O respetivo conteudo é inicializado a 0.</p> + +<h3 id="Excepções">Excepções</h3> + +<p>A {{jsxref("RangeError")}} é lançada caso o tamanho (<code>length) </code>é maior do que<code> </code>{{jsxref("Number.MAX_SAFE_INTEGER")}} (>= 2 ** 53) ou caso seja negativo.</p> + +<h2 id="Descrição">Descrição</h2> + +<p>O construtor de <code>ArrayBuffer</code> cria um novo objeto do tipo <code>ArrayBuffer</code> com o tamanho especificado em bytes.</p> + +<h3 id="Obter_um_array_buffer_a_partir_de_dados_existentes">Obter um array buffer a partir de dados existentes</h3> + +<ul> + <li><a href="/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding#Appendix.3A_Decode_a_Base64_string_to_Uint8Array_or_ArrayBuffer">From a Base64 string</a></li> + <li><a href="/en-US/docs/Web/API/FileReader#readAsArrayBuffer()">From a local file</a></li> +</ul> + +<h2 id="Propriedades">Propriedades</h2> + +<dl> + <dt><code>ArrayBuffer.length</code></dt> + <dd>Propriedade length do construtor de <code>ArrayBuffer </code>cujo valor é 1.</dd> + <dt>{{jsxref("ArrayBuffer.@@species", "get ArrayBuffer[@@species]")}}</dt> + <dd>A função do contrutor que é usado para criar objetos derivados.</dd> + <dt>{{jsxref("ArrayBuffer.prototype")}}</dt> + <dd>Permite adicionar novas propriedades a todos os objetos do tipo <code>ArrayBuffer.</code></dd> +</dl> + +<h2 id="Métodos">Métodos</h2> + +<dl> + <dt>{{jsxref("ArrayBuffer.isView", "ArrayBuffer.isView(arg)")}}</dt> + <dd>Devolve <code>true </code>caso <code>arg </code>é um tipo de representação do ArrayBuffer, como <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray">typed array objects</a> ou {{jsxref("DataView")}}. Devolve <code>false </code>caso contrário</dd> + <dt>{{jsxref("ArrayBuffer.transfer", "ArrayBuffer.transfer(oldBuffer [, newByteLength])")}} {{experimental_inline}}</dt> + <dd>Devolve um novo objeto <code>ArrayBuffer </code>cujo conteúdo é obtido do <code>oldBuffer </code>e ou é truncado ou preenchido a zeros pelo <code> newByteLength.</code></dd> +</dl> + +<h2 id="Instâncias_ArrayBuffer">Instâncias ArrayBuffer</h2> + +<p>Todas as instâncias de <code>ArrayBuffer</code> herdam de {{jsxref("ArrayBuffer.prototype")}}.</p> + +<h3 id="Propriedades_2">Propriedades</h3> + +<p>{{page('en-US/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/prototype','Properties')}}</p> + +<h3 id="Métodos_2">Métodos</h3> + +<p>{{page('en-US/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/prototype','Methods')}}</p> + +<dl> + <dt>{{jsxref("ArrayBuffer.slice()")}} {{non-standard_inline}}</dt> + <dd>Tem a mesma funcionalidade que {{jsxref("ArrayBuffer.prototype.slice()")}}.</dd> +</dl> + +<h2 id="Exemplo">Exemplo</h2> + +<p>Neste exemplo, criamos um buffer de 8 bytes com representação {{jsxref("Global_Objects/Int32Array", "Int32Array")}} a referênciar o buffer:</p> + +<pre class="brush: js">var buffer = new ArrayBuffer(8); +var view = new Int32Array(buffer);</pre> + +<h2 id="Especificação">Especificação</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Status</th> + <th scope="col">Comentário</th> + </tr> + <tr> + <td>{{SpecName('Typed Array')}}</td> + <td>{{Spec2('Typed Array')}}</td> + <td>Substituido por ECMAScript 6.</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-arraybuffer-constructor', 'ArrayBuffer')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> + <p>Definição inicial no stardard da ECMA. Especificar que <code>new </code>era necessário.</p> + </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-arraybuffer-constructor', 'ArrayBuffer')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_nos_navegadores">Compatibilidade nos navegadores</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>7.0</td> + <td>{{CompatGeckoDesktop("2")}}</td> + <td>10</td> + <td>11.6</td> + <td>5.1</td> + </tr> + <tr> + <td><code>ArrayBuffer()</code> without <code>new</code> throws</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop("44")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>ArrayBuffer.slice()</code> {{non-standard_inline}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}<br> + {{CompatNo}} {{CompatGeckoDesktop("53")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>4.0</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile("2")}}</td> + <td>10</td> + <td>11.6</td> + <td>4.2</td> + </tr> + <tr> + <td><code>ArrayBuffer()</code> without <code>new</code> throws</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile("44")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>ArrayBuffer.slice()</code> {{non-standard_inline}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}<br> + {{CompatNo}} {{CompatGeckoMobile("53")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Notas_de_compatibilidade">Notas de compatibilidade</h2> + +<p>Com ECMAScript 2015, construtores de <code>ArrayBuffer </code>são obrigados a usar o operador<code> </code>{{jsxref("Operators/new", "new")}}. Daqui adiante ao invocar <code>ArrayBuffer </code>como uma função sem<code> new </code>irá lançar uma exceção {{jsxref("TypeError")}}.</p> + +<pre class="brush: js example-bad">var dv = ArrayBuffer(10); +// TypeError: calling a builtin ArrayBuffer constructor +// without new is forbidden</pre> + +<pre class="brush: js example-good">var dv = new ArrayBuffer(10);</pre> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Typed_arrays">JavaScript typed arrays</a></li> + <li>{{jsxref("SharedArrayBuffer")}}</li> +</ul> 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 new file mode 100644 index 0000000000..4e454bacd9 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/global_objects/asyncfunction/index.html @@ -0,0 +1,124 @@ +--- +title: AsyncFunction +slug: Web/JavaScript/Reference/Global_Objects/AsyncFunction +translation_of: Web/JavaScript/Reference/Global_Objects/AsyncFunction +--- +<div>{{JSRef}}</div> + +<div>O constructor da função <strong>Async</strong> cria um novo objecto {{jsxref("Statements/async_function", "async function")}}. Em Javascript todas as funções asíncronas são na verdade objectos <code>AsyncFunction.</code></div> + +<p> </p> + +<p>Note-se que <code>AsyncFunction</code> não é um objecto global. Pode ser obtido da seguinte forma.</p> + +<pre class="brush: js">Object.getPrototypeOf(async function(){}).constructor +</pre> + +<h2 id="Síntaxe">Síntaxe</h2> + +<pre class="syntaxbox">new AsyncFunction([<var>arg1</var>[, <var>arg2</var>[, ...<var>argN</var>]],] <var>functionBody</var>)</pre> + +<h3 id="Parâmetros">Parâmetros</h3> + +<dl> + <dt><code>arg1, arg2, ... arg<em>N</em></code></dt> + <dd>Nomes usados pela função como nomes formais de argumentos . Cada um dos argumentos tem que ser uma <em>string</em> que corresponde a um identificador válido JavaScript ou uma lista separada por vírgulas; por exemplo "<code>x</code>", "<code>theValue</code>", ou "<code>a,b</code>".</dd> + <dt><code>functionBody</code></dt> + <dd>Uma <em>string</em> com os termos JavaScript que fazem parte da definição da função.</dd> +</dl> + +<h2 id="Descrição">Descrição</h2> + +<p>Os objectos {{jsxref("Statements/async_function", "async function")}} criados com o <em>constructor</em> <code>AsyncFunction</code> passam por um <em>parsing</em> 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 <em>parsing</em> ao mesmo tempo que o resto do código.</p> + +<p>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.</p> + +<div class="note"> +<p><strong>Nota:</strong> {{jsxref("Statements/async_function", "async functions")}} criado com o <em>constructor</em> <code>AsyncFunction</code> não estão encapsulados ao contexto da sua criação, são sempre criados no âmbito global.</p> + +<p>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 <code>AsyncFunction</code> foi chamado. Isto é diferente de chamar {{jsxref("Global_Objects/eval", "eval")}} com código para uma função asíncrona.</p> +</div> + +<p>A invocação do constructor <code>AsyncFunction</code> como uma função, i.e. sem usar o operador <code>new</code> tem o mesmo efeito que invocá-lo como <em>constructor</em>.</p> + +<p>Invoking the <code>AsyncFunction</code> constructor as a function (without using the <code>new</code> operator) has the same effect as invoking it as a constructor.</p> + +<h2 id="Propriedades">Propriedades</h2> + +<dl> + <dt><code><strong>AsyncFunction.length</strong></code></dt> + <dd>A propriedade comprimento do <em>constructor</em> do <code>AsyncFunction</code>, cujo valor é 1.</dd> + <dt>{{jsxref("AsyncFunction.prototype")}}</dt> + <dd>Permite adicionar propriedades a todos os objectos que são funções asíncronas.</dd> +</dl> + +<h2 id="AsyncFunction_prototype_object"><code>AsyncFunction</code> prototype object</h2> + +<h3 id="Propriedades_2">Propriedades</h3> + +<div>{{page('/pt-PT/docs/Web/JavaScript/Reference/Global_Objects/AsyncFunction/prototype', 'Properties')}}</div> + +<h2 id="Instâncias_de_AsyncFunction">Instâncias de <code>AsyncFunction</code></h2> + +<p>As instâncias de <code>AsyncFunction</code> herdam métodos e propriedades do {{jsxref("AsyncFunction.prototype")}}. Tal como com qualquer <em>constructor</em> pode-se mudar o <em>prototype object</em> para aplicar mudanças a todos as instâncias de <code>AsyncFunction</code>.</p> + +<h2 id="Exemplos">Exemplos</h2> + +<h3 id="Exemplo_de_criação_de_uma_função_async_a_partir_de_um_constructor_AsyncFunction">Exemplo de criação de uma função <em>async</em> a partir de um <em>constructor</em> <code>AsyncFunction</code></h3> + +<pre class="brush: js">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 +}); +</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('ESDraft', '#sec-async-function-objects', 'AsyncFunction object')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td>Definição inicial em ES2017.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_de_navegadores">Compatibilidade de navegadores</h2> + +<div> + + +<p>{{Compat("javascript.builtins.AsyncFunction")}}</p> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Statements/async_function", "async function function")}}</li> + <li>{{jsxref("Operators/async_function", "async function expression")}}</li> + <li>{{jsxref("Global_Objects/Function", "Function")}}</li> + <li>{{jsxref("Statements/function", "function statement")}}</li> + <li>{{jsxref("Operators/function", "function expression")}}</li> + <li>{{jsxref("Functions_and_function_scope", "Functions and function scope", "", 1)}}</li> +</ul> diff --git a/files/pt-pt/web/javascript/reference/global_objects/asyncfunction/prototype/index.html b/files/pt-pt/web/javascript/reference/global_objects/asyncfunction/prototype/index.html new file mode 100644 index 0000000000..8a085d6986 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/global_objects/asyncfunction/prototype/index.html @@ -0,0 +1,55 @@ +--- +title: AsyncFunction.prototype +slug: Web/JavaScript/Reference/Global_Objects/AsyncFunction/prototype +translation_of: Web/JavaScript/Reference/Global_Objects/AsyncFunction/prototype +--- +<div>{{JSRef}}</div> + +<p>A propriedade <code><strong>AsyncFunction.prototype</strong></code> representa o objecto <em>prototype</em> {{jsxref("AsyncFunction")}}.</p> + +<h2 id="Description">Description</h2> + +<p>Os objectos {{jsxref("AsyncFunction")}} são herdados de <code>AsyncFunction.prototype</code> e não podem ser modificados.</p> + +<h2 id="Propriedades">Propriedades</h2> + +<dl> + <dt><code><strong>AsyncFunction.constructor</strong></code></dt> + <dd>O valor inicial é {{jsxref("AsyncFunction")}}.</dd> + <dt><code><strong>AsyncFunction.prototype[@@toStringTag]</strong></code></dt> + <dd>Retorna "AsyncFunction".</dd> +</dl> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('ESDraft', '#sec-async-function-constructor-prototype', 'AsyncFunction.prototype')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td>Definição inicial ES2017.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_entre_navegadores">Compatibilidade entre navegadores</h2> + +<div> + + +<p>{{Compat("javascript.builtins.AsyncFunction.prototype")}}</p> +</div> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li>{{jsxref("AsyncFunction")}}</li> + <li>{{jsxref("Function")}}</li> +</ul> 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 new file mode 100644 index 0000000000..e8482a2c0e --- /dev/null +++ b/files/pt-pt/web/javascript/reference/global_objects/boolean/index.html @@ -0,0 +1,156 @@ +--- +title: Booliano +slug: Web/JavaScript/Reference/Global_Objects/Boolean +tags: + - Boolean + - Booliano + - Constructor + - JavaScript +translation_of: Web/JavaScript/Reference/Global_Objects/Boolean +--- +<div>{{JSRef}}</div> + +<p>O objeto <strong><code>Boolean</code></strong> é um <em>wrapper</em> objeto para um valor booliano.</p> + +<h2 id="Sintaxe">Sintaxe</h2> + +<pre class="syntaxbox">new Boolean([<var>value</var>])</pre> + +<h3 id="Parâmetros">Parâmetros</h3> + +<dl> + <dt><em><code>value</code></em></dt> + <dd>Opcional. O valor incial do objeto <em><code>Boolean</code></em>.</dd> +</dl> + +<h2 id="Descrição">Descrição</h2> + +<p>The value passed as the first parameter is converted to a boolean value, if necessary. If the value is omitted or is <code>0</code>, <code>-0</code>, {{jsxref("null")}}, <code>false</code>, {{jsxref("NaN")}}, {{jsxref("undefined")}}, or the empty string (<code>""</code>), the object has an initial value of <code>false</code>. If the DOM object {{domxref("document.all")}} is passed as a parameter, the new boolean object also has an initial value of <code>false</code>. All other values, including any object or the string <code>"false"</code>, create an object with an initial value of <code>true</code>.</p> + +<p>Do not confuse the primitive <code>Boolean</code> values <code>true</code> and <code>false</code> with the <code>true</code> and <code>false</code> values of the <code>Boolean</code> object.</p> + +<p>Any object of which the value is not {{jsxref("undefined")}} or {{jsxref("null")}}, including a <code>Boolean</code> object whose value is <code>false</code>, evaluates to <code>true</code> when passed to a conditional statement. For example, the condition in the following {{jsxref("Statements/if...else", "if")}} statement evaluates to <code>true</code>:</p> + +<pre class="brush: js">var x = new Boolean(false); +if (x) { + // this code is executed +} +</pre> + +<p>This behavior does not apply to <code>Boolean</code> primitives. For example, the condition in the following {{jsxref("Statements/if...else", "if")}} statement evaluates to <code>false</code>:</p> + +<pre class="brush: js">var x = false; +if (x) { + // this code is not executed +} +</pre> + +<p>Do not use a <code>Boolean</code> object to convert a non-boolean value to a boolean value. Instead, use <code>Boolean</code> as a function to perform this task:</p> + +<pre class="brush: js">var x = Boolean(expression); // preferred +var x = new Boolean(expression); // don't use +</pre> + +<p>If you specify any object, including a <code>Boolean</code> object whose value is <code>false</code>, as the initial value of a <code>Boolean</code> object, the new <code>Boolean</code> object has a value of <code>true</code>.</p> + +<pre class="brush: js">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 +</pre> + +<p>Do not use a <code>Boolean</code> object in place of a <code>Boolean</code> primitive.</p> + +<h2 id="Propriedades">Propriedades</h2> + +<dl> + <dt><code>Boolean.length</code></dt> + <dd>Length property whose value is 1.</dd> + <dt>{{jsxref("Boolean.prototype")}}</dt> + <dd>Represents the prototype for the <code>Boolean</code> constructor.</dd> +</dl> + +<h2 id="Métodos">Métodos</h2> + +<p>While the global <code>Boolean</code> object contains no methods of its own, it does inherit some methods through the prototype chain:</p> + +<h2 id="Instâncias_Boolean">Instâncias <em><code>Boolean</code></em></h2> + +<p>All <code>Boolean</code> instances inherit from {{jsxref("Boolean.prototype")}}. As with all constructors, the prototype object dictates instances' inherited properties and methods.</p> + +<h3 id="Propridades">Propridades</h3> + +<div>{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean/prototype', 'Properties')}}</div> + +<h3 id="Métodos_2">Métodos</h3> + +<div>{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean/prototype', 'Methods')}}</div> + +<h2 id="Exemplos">Exemplos</h2> + +<h3 id="Criar_objetos_Boolean_com_um_valor_inicial_de_false">Criar objetos <em><code>Boolean</code> </em>com um valor inicial de <em><code>false</code></em></h3> + +<pre class="brush: js">var bNoParam = Boolean(); +var bZero = Boolean(0); +var bNull = Boolean(null); +var bEmptyString = Boolean(''); +var bfalse = Boolean(false); +</pre> + +<h3 id="Criar_objetos_Boolean_com_um_valor_inicial_de_verdadeiro">Criar objetos <em><code>Boolean</code> </em>com um valor inicial de <em><code>verdadeiro</code></em></h3> + +<pre class="brush: js">var btrue = Boolean(true); +var btrueString = Boolean('true'); +var bfalseString = Boolean('false'); +var bSuLin = Boolean('Su Lin'); +var bArrayProto = Boolean([]); +var bObjProto = Boolean({}); +</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.0.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.6', 'Boolean')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-boolean-objects', 'Boolean')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-boolean-objects', 'Boolean')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_de_navegador">Compatibilidade de navegador</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Boolean")}}</p> +</div> + +<h2 id="Consulte_também">Consulte também</h2> + +<ul> + <li>{{jsxref("Boolean.prototype")}}</li> + <li>{{Glossary("Booliano")}}</li> + <li><a href="https://pt.wikipedia.org/wiki/Booleano">Tipo de dados Booliano (Wikipedia)</a></li> +</ul> 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 new file mode 100644 index 0000000000..5f8c84ca8e --- /dev/null +++ b/files/pt-pt/web/javascript/reference/global_objects/encodeuri/index.html @@ -0,0 +1,152 @@ +--- +title: encodeURI() +slug: Web/JavaScript/Reference/Global_Objects/encodeURI +translation_of: Web/JavaScript/Reference/Global_Objects/encodeURI +--- +<div>{{jsSidebar("Objects")}}</div> + +<p>O método <code><strong>encodeURI()</strong></code> 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").</p> + +<h2 id="Sintaxe">Sintaxe</h2> + +<pre class="syntaxbox"><code>encodeURI(<em>URI</em>)</code></pre> + +<h3 id="Parâmetros">Parâmetros</h3> + +<dl> + <dt><code>URI</code></dt> + <dd>Um Uniform Resource Identifier completo.</dd> +</dl> + +<h2 id="Descrição">Descrição</h2> + +<p>Assumindo que o URI é um URI completo, não serão codificados caracteres reservados que tenham significado especial no URI.</p> + +<p><code>encodeURI</code> substitui todos os caracteres <strong>excepto</strong> as seguintes sequências de escape UTF-8:</p> + +<table class="standard-table"> + <tbody> + <tr> + <td class="header">Tipo</td> + <td class="header">Incluído</td> + </tr> + <tr> + <td>Caracteres reservados</td> + <td><code>;</code> <code>,</code> <code>/</code> <code>?</code> <code>:</code> <code>@</code> <code>&</code> <code>=</code> <code>+</code> <code>$</code></td> + </tr> + <tr> + <td>Caracteres excluídos</td> + <td>alfabéticos, dígitos decimais , <code>-</code> <code>_</code> <code>.</code> <code>!</code> <code>~</code> <code>*</code> <code>'</code> <code>(</code> <code>)</code></td> + </tr> + <tr> + <td>Ponto</td> + <td><code>#</code></td> + </tr> + </tbody> +</table> + +<p>Note-se que o método <code>encodeURI</code> <em>não consegue</em> 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.</p> + +<p>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.,</p> + +<pre class="brush: js">// 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')); </pre> + +<p>Note-se também que caso se pretenda seguir a mais recente norma para URLs <a href="http://tools.ietf.org/html/rfc3986">RFC3986</a>, 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:</p> + +<pre class="brush: js">function fixedEncodeURI (str) { + return encodeURI(str).replace(/%5B/g, '[').replace(/%5D/g, ']'); +}</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + <tr> + <td>{{SpecName('ES3')}}</td> + <td>{{Spec2('ES3')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.1.3.3', 'encodeURI')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-encodeuri-uri', 'encodeURI')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_com_navegador">Compatibilidade com navegador</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Funcionalidade</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Suporte básico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Funcionalidade</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Suporte básico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Veja_também">Veja também</h2> + +<ul> + <li>{{jsxref("decodeURI")}}</li> + <li>{{jsxref("encodeURIComponent")}}</li> + <li>{{jsxref("decodeURIComponent")}}</li> +</ul> 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 new file mode 100644 index 0000000000..4c9bf9e96e --- /dev/null +++ b/files/pt-pt/web/javascript/reference/global_objects/function/arguments/index.html @@ -0,0 +1,88 @@ +--- +title: Function.arguments +slug: Web/JavaScript/Reference/Global_Objects/Function/arguments +translation_of: Web/JavaScript/Reference/Global_Objects/Function/arguments +--- +<div>{{JSRef}} {{deprecated_header}}</div> + +<div>A propriedade <strong><code><em>function.arguments</em></code></strong> refere-se a um objecto com aspecto de <em>array</em> que corresponde aos argumentos da função. Ao invés disso, use a variável {{jsxref("Functions/arguments", "arguments")}}. Esta propriedade é proibida no modo <em>strict</em> devido ao <em><a href="http://www.ecma-international.org/ecma-262/6.0/#sec-addrestrictedfunctionproperties">tail call optimization</a></em>.</div> + +<h2 id="Descrição">Descrição</h2> + +<p>A síntaxe <code>function.arguments</code> 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")}}.</p> + +<p>No caso de recursão isto é, se uma funão <code>f</code> aparece várias vezes na <em>stack, </em>o valor de <code>f.arguments</code> representa os argumentos correspondentes à mais recente chamada da função.</p> + +<p>O valor da propriedade <code>arguments</code> é tipicamente <em>null</em> se não há nenuma invocação da função a acontecer, ou seja, a função foi chamada mas ainda não retornou.</p> + +<h2 id="Exemplos">Exemplos</h2> + +<pre class="brush: js">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 +</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td> + <p>Definição inicial. Implementado em JavaScript 1.0. Tornado obsoleto a favor de {{jsxref("Functions/arguments", "arguments")}} em ES3.</p> + </td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-10.6', 'arguments object')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>Objecto {{jsxref("Functions/arguments", "arguments")}}</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-arguments-object', 'arguments object')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>Objecto {{jsxref("Functions/arguments", "arguments")}}</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-arguments-object', 'arguments object')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td>Objecto {{jsxref("Functions/arguments", "arguments")}}</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_navegadores">Compatibilidade navegadores</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Function.arguments")}}</p> +</div> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li>Objecto {{jsxref("Functions/arguments", "arguments")}}</li> + <li>{{jsxref("Functions", "Functions and function scope", "", 1)}}</li> +</ul> 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 new file mode 100644 index 0000000000..fa3faee130 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/global_objects/function/call/index.html @@ -0,0 +1,164 @@ +--- +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 +--- +<div>{{JSRef}}</div> + +<p>O método <code><strong>call()</strong></code> realiza a chamada de uma função com o parâmetros <code>this</code> além de outros parâmetros fornecidos individualmente.</p> + +<div>{{EmbedInteractiveExample("pages/js/function-call.html")}}</div> + + + +<h2 id="Sintaxe">Sintaxe</h2> + +<pre class="syntaxbox notranslate"><var>func</var>.call([<var>thisArg</var>[, <var>arg1</var>, <var>arg2</var>, ...<var>argN</var>]])</pre> + +<h3 id="Parâmetros">Parâmetros</h3> + +<dl> + <dt><em><code>thisArg</code></em> {{optional_inline}}</dt> + <dd>O valor de <code>this</code> fornecido ao chamar <code><em>func</em></code>.</dd> +</dl> + +<div class="blockIndicator note"> +<p>Aviso: Em certos casos, <em><code>thisArg</code></em> pode não ser o valor que o método vê.</p> + +<p>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.</p> +</div> + +<dl> + <dt><em><code>arg1, arg2, ...argN</code></em> {{optional_inline}}</dt> + <dd>Parâmetros para a função.</dd> +</dl> + +<h3 id="Resultado">Resultado</h3> + +<p>O resultado ao chamar a função em questão com os parâmetros <code>this</code> e os outros argumentos especificados.</p> + +<h2 id="Descrição">Descrição</h2> + +<p><code>call()</code> permite uma função / método pertencendo a um objeto, ser atribuída a outro objeto e ser chamada desse mesmo.</p> + +<p><code>call()</code> fornece um novo valor para <code>this</code> à função / método. Com <code>call()</code>, 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.</p> + +<div class="blockIndicator note"> +<p>Nota: Apesar de a sintaxe da função ser quase idêntica à da {{jsxref("Function.prototype.apply", "apply()")}}, a principal diferença é que <code>call()</code> aceita uma <strong>lista de argumentos</strong> (<code>arg1, arg2, ...argN</code>), enquanto <code>apply()</code> aceita <strong>uma matriz de argumentos</strong> (<code>[arg1, arg2, ...argN]</code>).</p> +</div> + +<h2 id="Exemplos">Exemplos</h2> + +<h3 id="Usar_call_para_encadear_construtores_dum_objeto">Usar <code>call</code> para encadear construtores dum objeto</h3> + +<p>É possível utilizar <code>call</code> para encadear construtores para um objeto (como em Java).</p> + +<p>No exemplo abaixo, o construtor para o objeto <code>Product</code> é definido com dois parâmetros: <code>name</code> e <code>price</code>.</p> + +<p>Duas outras funções, <code>Food</code> e <code>Toy</code>, invocam <code>Product</code> passando os parâmetros <code>this</code><font face="Open Sans, arial, sans-serif">, </font><code>name</code> e <code>price</code>. As funções <code>Food</code> e <code>Toy</code> também definem a propriadade <code>category</code>.</p> + +<pre class="brush: js notranslate">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);</pre> + +<h3 id="Usar_call_para_invocar_uma_função_anónima">Usar <code>call</code> para invocar uma função anónima</h3> + +<p>Neste exemplo, criamos uma função anónima e utilizamos <code>call</code> para invocá-la em cada objeto na matriz.</p> + +<p>O principal objetivo da função anónima é inserir a função <code>print</code> em cada objeto. A função <code>print</code> imprimir o índice do objeto na matriz em que se encontra.</p> + +<div class="blockIndicator note"> +<p>Passar o objeto desta forma (como <code>this</code>) não é necessário, mas foi feito de forma a exemplificar a função.</p> +</div> + +<pre class="brush: js notranslate">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); +} +</pre> + +<h3 id="Usar_call_para_invocar_a_função_sem_especificar_o_primeiro_argumento">Usar <code>call</code> para invocar a função sem especificar o primeiro argumento</h3> + +<p>No exemplo abaixo, quando chamamos a função <code>display</code> sem passar o primeiro argumento. Se o primeiro argumento não é especificado, o objeto global é atribuído a <code>this</code>.<br> + </p> + +<pre class="brush: js notranslate">var sData = 'Wisen'; + +function display() { + console.log('sData value is %s ', this.sData); +} + +display.call(); // sData value is Wisen</pre> + +<div class="note"> +<p><strong>Aviso:</strong> Em "strict mode", o valor de <code>this</code> é <code>undefined</code>, exemplificado em baixo.</p> +</div> + +<pre class="brush: js notranslate">'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</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificação</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('ESDraft', '#sec-function.prototype.call', 'Function.prototype.call')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + + + +<p>{{Compat("javascript.builtins.Function.call")}}</p> + +<h2 id="Veja_também">Veja também</h2> + +<ul> + <li>{{jsxref("Function.prototype.bind()")}}</li> + <li>{{jsxref("Function.prototype.apply()")}}</li> + <li> + <p><a href="/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript">Introduction to Object-Oriented JavaScript</a></p> + </li> +</ul> 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 new file mode 100644 index 0000000000..6ebfd66c44 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/global_objects/function/index.html @@ -0,0 +1,192 @@ +--- +title: Function +slug: Web/JavaScript/Reference/Global_Objects/Function +tags: + - Constructor + - Function + - JavaScript + - NeedsTranslation + - TopicStub +translation_of: Web/JavaScript/Reference/Global_Objects/Function +--- +<div>{{JSRef}}</div> + +<p>The <strong><code>Function</code> constructor</strong> creates a new <code>Function</code> object. In JavaScript every function is actually a <code>Function</code> object.</p> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox"><code>new Function ([<var>arg1</var>[, <var>arg2</var>[, ...<var>argN</var>]],] <var>functionBody</var>)</code></pre> + +<h3 id="Parameters">Parameters</h3> + +<dl> + <dt><code>arg1, arg2, ... arg<em>N</em></code></dt> + <dd>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 "<code>x</code>", "<code>theValue</code>", or "<code>a,b</code>".</dd> + <dt><code>functionBody</code></dt> + <dd>A string containing the JavaScript statements comprising the function definition.</dd> +</dl> + +<h2 id="Description">Description</h2> + +<p><code>Function</code> objects created with the <code>Function</code> constructor are parsed when the function is created. This is less efficient than declaring a function with a <a href="/en-US/docs/Web/JavaScript/Reference/Operators/function">function expression</a> or <a href="/en-US/docs/Web/JavaScript/Reference/Statements/function">function statement</a> and calling it within your code, because such functions are parsed with the rest of the code.</p> + +<p>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.</p> + +<p>Invoking the <code>Function</code> constructor as a function (without using the <code>new</code> operator) has the same effect as invoking it as a constructor.</p> + +<h2 id="Properties_and_Methods_of_Function">Properties and Methods of <code>Function</code></h2> + +<p>The global <code>Function</code> 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")}}.</p> + +<h2 id="Function_prototype_object"><code>Function</code> prototype object</h2> + +<h3 id="Properties">Properties</h3> + +<div>{{page('/en-US/docs/JavaScript/Reference/Global_Objects/Function/prototype', 'Properties')}}</div> + +<h3 id="Methods">Methods</h3> + +<div>{{page('/en-US/docs/JavaScript/Reference/Global_Objects/Function/prototype', 'Methods')}}</div> + +<h2 id="Function_instances"><code>Function</code> instances</h2> + +<p><code>Function</code> 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 <code>Function</code> instances.</p> + +<h2 id="Examples">Examples</h2> + +<h3 id="Specifying_arguments_with_the_Function_constructor">Specifying arguments with the <code>Function</code> constructor</h3> + +<p>The following code creates a <code>Function</code> object that takes two arguments.</p> + +<pre class="brush: js">// 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 +</pre> + +<p>The arguments "<code>a</code>" and "<code>b</code>" are formal argument names that are used in the function body, "<code>return a + b</code>".</p> + +<h3 id="Difference_between_Function_constructor_and_function_declaration">Difference between Function constructor and function declaration</h3> + +<p>Functions created with the <code>Function</code> 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 <code>Function</code> constructor was called. This is different from using {{jsxref("eval")}} with code for a function expression.</p> + +<pre class="brush: js">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 +</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.0.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.3', 'Function')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-function-objects', 'Function')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-function-objects', 'Function')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Functions", "Functions and function scope")}}</li> + <li>{{jsxref("Function")}}</li> + <li>{{jsxref("Statements/function", "function statement")}}</li> + <li>{{jsxref("Operators/function", "function expression")}}</li> + <li>{{jsxref("Statements/function*", "function* statement")}}</li> + <li>{{jsxref("Operators/function*", "function* expression")}}</li> + <li>{{jsxref("GeneratorFunction")}}</li> +</ul> diff --git a/files/pt-pt/web/javascript/reference/global_objects/index.html b/files/pt-pt/web/javascript/reference/global_objects/index.html new file mode 100644 index 0000000000..f3850bdfd2 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/global_objects/index.html @@ -0,0 +1,173 @@ +--- +title: Objetos integrados padrão +slug: Web/JavaScript/Reference/Global_Objects +tags: + - Built-in + - JavaScript + - Objects + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects +--- +<div>{{jsSidebar("Objects")}}</div> + +<h2 id="Summary" name="Summary">Resumo</h2> + +<p>Este capítulo documenta todos os objectos built-in do JavaScript standard, juntamente com os seus métodos e propriedades.</p> + +<div class="onlyinclude"> +<p>O termo "objectos globais" (ou objectos built-in standard) não é para ser confundido com <em>objecto global</em>. 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 <code>undefined</code>). O próprio <em>global object</em> 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).</p> + +<p>Outros objectos no scope global são <a href="/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#Creating_new_objects">criados através do script do utilizador</a> or fornecidos pela aplicação host. Os objectos do host disponíveis no contexto browser são documentados na <a href="/en-US/docs/Web/API/Reference">referência da API</a>. Para mais informações sobre a distinção entre <a href="/en-US/docs/DOM/DOM_Reference">DOM</a> e o núcleo do <a href="/en-US/docs/Web/JavaScript">JavaScript</a>, ver <a href="/en-US/docs/Web/JavaScript/JavaScript_technologies_overview">exposição das tecnologias do JavaScript</a>.</p> + +<h2 id="Objetos_padrão_(por_categoria)">Objetos padrão (por categoria)</h2> + +<h3 id="Propriedades_do_valor">Propriedades do valor</h3> + +<p>Estas propriedades globais devolvem um valor simples; estas não têm propriedades ou métodos.</p> + +<ul> + <li>{{jsxref("Infinity")}}</li> + <li>{{jsxref("NaN")}}</li> + <li>{{jsxref("undefined")}}</li> + <li>{{jsxref("null")}} literal</li> +</ul> + +<h3 id="Propriedades_da_função">Propriedades da função</h3> + +<p>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.</p> + +<ul> + <li>{{jsxref("Global_Objects/eval", "eval()")}}</li> + <li>{{jsxref("Global_Objects/uneval", "uneval()")}} {{non-standard_inline()}}</li> + <li>{{jsxref("Global_Objects/isFinite", "isFinite()")}}</li> + <li>{{jsxref("Global_Objects/isNaN", "isNaN()")}}</li> + <li>{{jsxref("Global_Objects/parseFloat", "parseFloat()")}}</li> + <li>{{jsxref("Global_Objects/parseInt", "parseInt()")}}</li> + <li>{{jsxref("Global_Objects/decodeURI", "decodeURI()")}}</li> + <li>{{jsxref("Global_Objects/decodeURIComponent", "decodeURIComponent()")}}</li> + <li>{{jsxref("Global_Objects/encodeURI", "encodeURI()")}}</li> + <li>{{jsxref("Global_Objects/encodeURIComponent", "encodeURIComponent()")}}</li> + <li>{{jsxref("Global_Objects/escape", "escape()")}} {{deprecated_inline()}}</li> + <li>{{jsxref("Global_Objects/unescape", "unescape()")}} {{deprecated_inline()}}</li> +</ul> + +<h3 id="Objetos_fundamentais">Objetos fundamentais</h3> + +<p>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.</p> + +<ul> + <li>{{jsxref("Object")}}</li> + <li>{{jsxref("Function")}}</li> + <li>{{jsxref("Boolean")}}</li> + <li>{{jsxref("Symbol")}} {{experimental_inline()}}</li> + <li>{{jsxref("Error")}}</li> + <li>{{jsxref("EvalError")}}</li> + <li>{{jsxref("InternalError")}}</li> + <li>{{jsxref("RangeError")}}</li> + <li>{{jsxref("ReferenceError")}}</li> + <li>{{jsxref("StopIteration")}}</li> + <li>{{jsxref("SyntaxError")}}</li> + <li>{{jsxref("TypeError")}}</li> + <li>{{jsxref("URIError")}}</li> +</ul> + +<h3 id="Números_e_datas">Números e datas</h3> + +<p>Objectos que lidam com números, datas e cálculos matemáticos.</p> + +<ul> + <li>{{jsxref("Number")}}</li> + <li>{{jsxref("Math")}}</li> + <li>{{jsxref("Date")}}</li> +</ul> + +<h3 id="Processamento_de_texto">Processamento de texto</h3> + +<p>Objectos para manipular texto.</p> + +<ul> + <li>{{jsxref("String")}}</li> + <li>{{jsxref("RegExp")}}</li> +</ul> + +<h3 id="Coleções_indexadas">Coleções indexadas</h3> + +<p>Coleções ordenadas por um indíce. Objectos do tipo array.</p> + +<ul> + <li>{{jsxref("Array")}}</li> + <li>{{jsxref("Int8Array")}}</li> + <li>{{jsxref("Uint8Array")}}</li> + <li>{{jsxref("Uint8ClampedArray")}}</li> + <li>{{jsxref("Int16Array")}}</li> + <li>{{jsxref("Uint16Array")}}</li> + <li>{{jsxref("Int32Array")}}</li> + <li>{{jsxref("Uint32Array")}}</li> + <li>{{jsxref("Float32Array")}}</li> + <li>{{jsxref("Float64Array")}}</li> + <li>{{jsxref("ParallelArray")}} {{non-standard_inline()}}</li> +</ul> + +<h3 id="Coleções_por_chave">Coleções por chave</h3> + +<p>Coleções de objectos como chaves. Elementos iteráveis por ordem de inserção.</p> + +<ul> + <li>{{jsxref("Map")}} {{experimental_inline()}}</li> + <li>{{jsxref("Set")}} {{experimental_inline()}}</li> + <li>{{jsxref("WeakMap")}} {{experimental_inline()}}</li> + <li>{{jsxref("WeakSet")}} {{experimental_inline()}}</li> +</ul> + +<h3 id="Dados_estruturados">Dados estruturados</h3> + +<p>Buffers de dados e <strong>J</strong>ava<strong>S</strong>cript <strong>O</strong>bject <strong>N</strong>otation (JSON).</p> + +<ul> + <li>{{jsxref("ArrayBuffer")}}</li> + <li>{{jsxref("DataView")}}</li> + <li>{{jsxref("JSON")}}</li> +</ul> + +<h3 id="Objectos_de_abstração_de_controlo">Objectos de abstração de controlo</h3> + +<ul> + <li>{{jsxref("Iterator")}} {{non-standard_inline()}}</li> + <li>{{jsxref("Generator")}} {{experimental_inline()}}</li> + <li>{{jsxref("Promise")}} {{experimental_inline()}}</li> +</ul> + +<h3 id="Reflexão">Reflexão</h3> + +<ul> + <li>{{jsxref("Reflect")}} {{experimental_inline()}}</li> + <li>{{jsxref("Proxy")}} {{experimental_inline()}}</li> +</ul> + +<h3 id="Internacionalização">Internacionalização</h3> + +<p>Adições ao núcleo do ECMAScript para funcionalidades de linguagens sensíveis.</p> + +<ul> + <li>{{jsxref("Intl")}}</li> + <li>{{jsxref("Global_Objects/Collator", "Intl.Collator")}}</li> + <li>{{jsxref("Global_Objects/DateTimeFormat", "Intl.DateTimeFormat")}}</li> + <li>{{jsxref("Global_Objects/NumberFormat", "Intl.NumberFormat")}}</li> +</ul> + +<h3 id="Objetos_não_padrão">Objetos não padrão</h3> + +<ul> + <li>{{jsxref("Iterator")}} {{non-standard_inline}}</li> + <li>{{jsxref("ParallelArray")}} {{non-standard_inline}}</li> + <li>{{jsxref("StopIteration")}} {{non-standard_inline}}</li> +</ul> + +<h3 id="Outros">Outros</h3> + +<ul> + <li><code><a href="/en-US/docs/Web/JavaScript/Reference/Functions/arguments">Argumentos</a></code></li> +</ul> +</div> + +<p> </p> 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 new file mode 100644 index 0000000000..818471e60e --- /dev/null +++ b/files/pt-pt/web/javascript/reference/global_objects/infinity/index.html @@ -0,0 +1,69 @@ +--- +title: Infinity +slug: Web/JavaScript/Reference/Global_Objects/Infinity +tags: + - JavaScript + - Propriedade + - Referencia +translation_of: Web/JavaScript/Reference/Global_Objects/Infinity +--- +<div>{{jsSidebar("Objects")}}</div> + +<p>A propriedade global <code><strong>Infinity</strong></code> é um valor numérico que representa o infinito.</p> + +<p>{{js_property_attributes(0,0,0)}}</p> + +<div>{{EmbedInteractiveExample("pages/js/globalprops-infinity.html")}}</div> + +<div class="hidden">The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> and send us a pull request.</div> + +<h2 id="Descrição">Descrição</h2> + +<p><code>Infinity</code> é uma propriedade do objeto <code>global</code>. Isto é para dizer que é um variável com um escopo global.</p> + +<p>O valor inicial do <code>Infinity</code> é {{jsxref("Number.POSITIVE_INFINITY")}}. O valor <code>Infinity</code> (infinito positivo) é maior que qualquer outro número.</p> + +<p>Este valor age de form diferente do infinito matematico; veja {{jsxref("Number.POSITIVE_INFINITY")}} para mais detalhes.</p> + +<p>Como definido na especificação ECMAScript 5, <code>Infinity</code> é <em>read-only</em> (implementado em JavaScript 1.8.5 / Firefox 4).</p> + +<h2 id="Exemplos">Exemplos</h2> + +<h3 id="Usar_Infinity">Usar Infinity</h3> + +<pre class="brush: js notranslate">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 */ +</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificação</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('ESDraft', '#sec-value-properties-of-the-global-object-infinity', 'Infinity')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade">Compatibilidade</h2> + + + +<p>{{Compat("javascript.builtins.Infinity")}}</p> + +<h2 id="Veja_também">Veja também</h2> + +<ul> + <li>{{jsxref("Number.NEGATIVE_INFINITY")}}</li> + <li>{{jsxref("Number.POSITIVE_INFINITY")}}</li> + <li>{{jsxref("Number.isFinite")}}</li> +</ul> 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 new file mode 100644 index 0000000000..c89b15567a --- /dev/null +++ b/files/pt-pt/web/javascript/reference/global_objects/math/ceil/index.html @@ -0,0 +1,161 @@ +--- +title: Math.ceil() +slug: Web/JavaScript/Reference/Global_Objects/Math/ceil +translation_of: Web/JavaScript/Reference/Global_Objects/Math/ceil +--- +<div>{{JSRef}}</div> + +<p>A função <strong><code>Math.ceil()</code></strong> 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. </p> + +<h2 id="Sintaxe">Sintaxe</h2> + +<pre class="syntaxbox"><code>Math.ceil(<var>x</var>)</code></pre> + +<h3 id="Parametros">Parametros</h3> + +<dl> + <dt><code>x</code></dt> + <dd>Um número.</dd> +</dl> + +<h3 id="Valor_de_retorno">Valor de retorno</h3> + +<p>Um inteiro smallest maior ou igual ao n.º passado como parâmetro.</p> + +<h2 id="Descrição">Descrição</h2> + +<p>Como <code>ceil()</code> é um método estático de <code>Math</code>, pode sempre ser usado como <code>Math.ceil()</code>, o objeto <code>Math</code> não é um construtor. </p> + +<h2 id="Exemplos">Exemplos</h2> + +<h3 id="Utilizando_Math.ceil">Utilizando <code>Math.ceil()</code></h3> + +<p>Seguem exemplos da utilização de <code>Math.ceil()</code>.</p> + +<pre class="brush: js">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 +</pre> + +<h3 id="Ajustamento_decimal">Ajustamento decimal </h3> + +<pre class="brush: js">// 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 +</pre> + +<h2 id="Especificações">Especificações </h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Definição inicial JavaScript 1.0.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.8.2.6', 'Math.ceil')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-math.ceil', 'Math.ceil')}}</td> + <td>{{Spec2('ES6')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-math.ceil', 'Math.ceil')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.Math.ceil")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Math.abs()")}}</li> + <li>{{jsxref("Math.floor()")}}</li> + <li>{{jsxref("Math.round()")}}</li> + <li>{{jsxref("Math.sign()")}}</li> + <li>{{jsxref("Math.trunc()")}}</li> +</ul> 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 new file mode 100644 index 0000000000..867c783782 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/global_objects/math/index.html @@ -0,0 +1,214 @@ +--- +title: Math +slug: Web/JavaScript/Reference/Global_Objects/Math +translation_of: Web/JavaScript/Reference/Global_Objects/Math +--- +<div>{{JSRef}}</div> + +<p><strong><code>Math</code></strong> é um objecto integrado que tem propriedades e métodos correspondentes a constantes e funções matemáticas. Não é um objecto função.</p> + +<h2 id="Descrição">Descrição</h2> + +<p>Contrariamente aos outros objectos globais, <code>Math</code> não é um construtor. Todas as propriedades e métodos de <code>Math</code> são estáticas. Refere-se a constante pi com <code>Math.PI</code> e chama-se a função de seno com <code>Math.sin(x)</code>, em que x é o argumento do método. As constantes estão definidas com a precisão completa dos números reais do JavaScript.</p> + +<p>Para extender o objecto <code>Math</code>, não se usa o protótipo. Em vez disso extende-se directamente o objecto <code>Math</code>:</p> + +<p>Math.nomeProp=valorProp;</p> + +<p>Math.nomeMetodo=refMetodo;</p> + +<h2 id="Propriedades">Propriedades</h2> + +<dl> + <dt>{{jsxref("Math.E")}}</dt> + <dd>Euler's constant and the base of natural logarithms, approximately 2.718.</dd> + <dt>{{jsxref("Math.LN2")}}</dt> + <dd>Natural logarithm of 2, approximately 0.693.</dd> + <dt>{{jsxref("Math.LN10")}}</dt> + <dd>Natural logarithm of 10, approximately 2.303.</dd> + <dt>{{jsxref("Math.LOG2E")}}</dt> + <dd>Base 2 logarithm of E, approximately 1.443.</dd> + <dt>{{jsxref("Math.LOG10E")}}</dt> + <dd>Base 10 logarithm of E, approximately 0.434.</dd> + <dt>{{jsxref("Math.PI")}}</dt> + <dd>Ratio of the circumference of a circle to its diameter, approximately 3.14159.</dd> + <dt>{{jsxref("Math.SQRT1_2")}}</dt> + <dd>Square root of 1/2; equivalently, 1 over the square root of 2, approximately 0.707.</dd> + <dt>{{jsxref("Math.SQRT2")}}</dt> + <dd>Square root of 2, approximately 1.414.</dd> +</dl> + +<h2 id="Métodos">Métodos</h2> + +<div class="note"> +<p>Note that the trigonometric functions (<code>sin()</code>, <code>cos()</code>, <code>tan()</code>, <code>asin()</code>, <code>acos()</code>, <code>atan()</code>, <code>atan2()</code>) expect or return angles in radians. To convert radians to degrees, divide by <code>(Math.PI / 180)</code>, and multiply by this to convert the other way.</p> +</div> + +<div class="note"> +<p>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.</p> +</div> + +<dl> + <dt>{{jsxref("Global_Objects/Math/abs", "Math.abs(x)")}}</dt> + <dd>Returns the absolute value of a number.</dd> + <dt>{{jsxref("Global_Objects/Math/acos", "Math.acos(x)")}}</dt> + <dd>Returns the arccosine of a number.</dd> + <dt>{{jsxref("Global_Objects/Math/acosh", "Math.acosh(x)")}}</dt> + <dd>Returns the hyperbolic arccosine of a number.</dd> + <dt>{{jsxref("Global_Objects/Math/asin", "Math.asin(x)")}}</dt> + <dd>Returns the arcsine of a number.</dd> + <dt>{{jsxref("Global_Objects/Math/asinh", "Math.asinh(x)")}}</dt> + <dd>Returns the hyperbolic arcsine of a number.</dd> + <dt>{{jsxref("Global_Objects/Math/atan", "Math.atan(x)")}}</dt> + <dd>Returns the arctangent of a number.</dd> + <dt>{{jsxref("Global_Objects/Math/atanh", "Math.atanh(x)")}}</dt> + <dd>Returns the hyperbolic arctangent of a number.</dd> + <dt>{{jsxref("Global_Objects/Math/atan2", "Math.atan2(y, x)")}}</dt> + <dd>Returns the arctangent of the quotient of its arguments.</dd> + <dt>{{jsxref("Global_Objects/Math/cbrt", "Math.cbrt(x)")}}</dt> + <dd>Returns the cube root of a number.</dd> + <dt>{{jsxref("Global_Objects/Math/ceil", "Math.ceil(x)")}}</dt> + <dd>Returns the smallest integer greater than or equal to a number.</dd> + <dt>{{jsxref("Global_Objects/Math/clz32", "Math.clz32(x)")}}</dt> + <dd>Returns the number of leading zeroes of a 32-bit integer.</dd> + <dt>{{jsxref("Global_Objects/Math/cos", "Math.cos(x)")}}</dt> + <dd>Returns the cosine of a number.</dd> + <dt>{{jsxref("Global_Objects/Math/cosh", "Math.cosh(x)")}}</dt> + <dd>Returns the hyperbolic cosine of a number.</dd> + <dt>{{jsxref("Global_Objects/Math/exp", "Math.exp(x)")}}</dt> + <dd>Returns E<sup>x</sup>, where <var>x</var> is the argument, and E is Euler's constant (2.718…), the base of the natural logarithm.</dd> + <dt>{{jsxref("Global_Objects/Math/expm1", "Math.expm1(x)")}}</dt> + <dd>Returns subtracting 1 from <code>exp(x)</code>.</dd> + <dt>{{jsxref("Global_Objects/Math/floor", "Math.floor(x)")}}</dt> + <dd>Returns the largest integer less than or equal to a number.</dd> + <dt>{{jsxref("Global_Objects/Math/fround", "Math.fround(x)")}}</dt> + <dd>Returns the nearest <a href="http://en.wikipedia.org/wiki/Single-precision_floating-point_format" title="link to the wikipedia page on single precision">single precision</a> float representation of a number.</dd> + <dt>{{jsxref("Global_Objects/Math/hypot", "Math.hypot([x[, y[, …]]])")}}</dt> + <dd>Returns the square root of the sum of squares of its arguments.</dd> + <dt>{{jsxref("Global_Objects/Math/imul", "Math.imul(x, y)")}}</dt> + <dd>Returns the result of a 32-bit integer multiplication.</dd> + <dt>{{jsxref("Global_Objects/Math/log", "Math.log(x)")}}</dt> + <dd>Returns the natural logarithm (log<sub>e</sub>, also ln) of a number.</dd> + <dt>{{jsxref("Global_Objects/Math/log1p", "Math.log1p(x)")}}</dt> + <dd>Returns the natural logarithm (log<sub>e</sub>, also ln) of <code>1 + x</code> for a number x.</dd> + <dt>{{jsxref("Global_Objects/Math/log10", "Math.log10(x)")}}</dt> + <dd>Returns the base 10 logarithm of a number.</dd> + <dt>{{jsxref("Global_Objects/Math/log2", "Math.log2(x)")}}</dt> + <dd>Returns the base 2 logarithm of a number.</dd> + <dt>{{jsxref("Global_Objects/Math/max", "Math.max([x[, y[, …]]])")}}</dt> + <dd>Returns the largest of zero or more numbers.</dd> + <dt>{{jsxref("Global_Objects/Math/min", "Math.min([x[, y[, …]]])")}}</dt> + <dd>Returns the smallest of zero or more numbers.</dd> + <dt>{{jsxref("Global_Objects/Math/pow", "Math.pow(x, y)")}}</dt> + <dd>Returns base to the exponent power, that is, <code>base<sup>exponent</sup></code>.</dd> + <dt>{{jsxref("Global_Objects/Math/random", "Math.random()")}}</dt> + <dd>Returns a pseudo-random number between 0 and 1.</dd> + <dt>{{jsxref("Global_Objects/Math/round", "Math.round(x)")}}</dt> + <dd>Returns the value of a number rounded to the nearest integer.</dd> + <dt>{{jsxref("Global_Objects/Math/sign", "Math.sign(x)")}}</dt> + <dd>Returns the sign of the x, indicating whether x is positive, negative or zero.</dd> + <dt>{{jsxref("Global_Objects/Math/sin", "Math.sin(x)")}}</dt> + <dd>Returns the sine of a number.</dd> + <dt>{{jsxref("Global_Objects/Math/sinh", "Math.sinh(x)")}}</dt> + <dd>Returns the hyperbolic sine of a number.</dd> + <dt>{{jsxref("Global_Objects/Math/sqrt", "Math.sqrt(x)")}}</dt> + <dd>Returns the positive square root of a number.</dd> + <dt>{{jsxref("Global_Objects/Math/tan", "Math.tan(x)")}}</dt> + <dd>Returns the tangent of a number.</dd> + <dt>{{jsxref("Global_Objects/Math/tanh", "Math.tanh(x)")}}</dt> + <dd>Returns the hyperbolic tangent of a number.</dd> + <dt><code>Math.toSource()</code> {{non-standard_inline}}</dt> + <dd>Returns the string <code>"Math"</code>.</dd> + <dt>{{jsxref("Global_Objects/Math/trunc", "Math.trunc(x)")}}</dt> + <dd>Returns the integral part of the number x, removing any fractional digits.</dd> +</dl> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.1.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.8', 'Math')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-math-object', 'Math')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>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.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-math-object', 'Math')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Number")}}</li> +</ul> 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 new file mode 100644 index 0000000000..9ac8497a44 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/global_objects/number/index.html @@ -0,0 +1,213 @@ +--- +title: Number +slug: Web/JavaScript/Reference/Global_Objects/Number +tags: + - JavaScript + - Number + - Reference + - TopicStub +translation_of: Web/JavaScript/Reference/Global_Objects/Number +--- +<div>{{JSRef}}</div> + +<p>O objecto JavaScript <strong><code>Number</code></strong> é um objecto abstraído que te permite trabalhar com valores numéricos. Um objecto <code>Number</code> é criado usando o constructor <code>Number().</code></p> + +<h2 id="Constructor">Constructor</h2> + +<pre class="syntaxbox">new Number(valor);</pre> + +<h3 id="Parâmetro">Parâmetro</h3> + +<dl> + <dt><code>valor</code></dt> + <dd>O valor numérico representado pelo objecto que está a ser criado.</dd> +</dl> + +<h2 id="Descrição">Descrição</h2> + +<p>Os usos mais comuns para o objecto <code>Number</code> são:</p> + +<ul> + <li>Se o argumento não puder ser convertido num número, retorna {{jsxref("NaN")}}.</li> + <li>Num contexto não-constructor (isto é, sem o operador {{jsxref("Operators/new", "new")}}), <code>Number</code> pode ser usado para uma conversão de tipo.</li> +</ul> + +<h2 id="Propriedades">Propriedades</h2> + +<dl> + <dt>{{jsxref("Number.EPSILON")}} {{experimental_inline}}</dt> + <dd>O intervalo mais pequeno entre dois números representáveis.</dd> + <dt>{{jsxref("Number.MAX_SAFE_INTEGER")}} {{experimental_inline}}</dt> + <dd>O maior inteiro bem representado em JavaScript (<code>2<sup>53</sup> - 1</code>).</dd> + <dt>{{jsxref("Number.MAX_VALUE")}}</dt> + <dd>O maior número positivo representável.</dd> + <dt>{{jsxref("Number.MIN_SAFE_INTEGER")}} {{experimental_inline}}</dt> + <dd>O menor inteiro bem representado em JavaScript (<code>-(2<sup>53</sup> - 1)</code>).</dd> + <dt>{{jsxref("Number.MIN_VALUE")}}</dt> + <dd>O menor número positivo representável - ou seja, o número positivo mais próximo de zero (sem ser o zero).</dd> + <dt>{{jsxref("Number.NaN")}}</dt> + <dd>Valor especial para representar um "não número".</dd> + <dt>{{jsxref("Number.NEGATIVE_INFINITY")}}</dt> + <dd>Valor especial para representar o infinito negativo; retornado em caso de overflow.</dd> + <dt>{{jsxref("Number.POSITIVE_INFINITY")}}</dt> + <dd>Valor especial para representar o infinito; retornado em caso de overflow.</dd> + <dt>{{jsxref("Number.prototype")}}</dt> + <dd>Permite adicionar propriedades ao objecto <code>Number</code>.</dd> +</dl> + +<h2 id="Métodos">Métodos</h2> + +<dl> + <dt>{{jsxref("Number.isNaN()")}} {{experimental_inline}}</dt> + <dd>Determina se o valor passado é NaN.</dd> + <dt>{{jsxref("Number.isFinite()")}} {{experimental_inline}}</dt> + <dd>Determina se o valor passado é um número finito.</dd> + <dt>{{jsxref("Number.isInteger()")}} {{experimental_inline}}</dt> + <dd>Determina se o número passado é um inteiro.</dd> + <dt>{{jsxref("Number.isSafeInteger()")}} {{experimental_inline}}</dt> + <dd>Determina se o valor passado é um inteiro bem representado (número entre <code>-(2<sup>53</sup> - 1)</code> e <code>2<sup>53</sup> - 1</code>).</dd> + <dt><s class="obsoleteElement">{{jsxref("Number.toInteger()")}} {{obsolete_inline}}</s></dt> + <dd><s class="obsoleteElement">Usado para avaliar o valor passado e convertê-lo num inteiro (ou {{jsxref("Global_Objects/Infinity", "Infinity")}}), mas foi removido.</s></dd> + <dt>{{jsxref("Number.parseFloat()")}} {{experimental_inline}}</dt> + <dd>O valor é o mesmo que {{jsxref("Global_Objects/parseFloat", "parseFloat()")}} de um objecto global.</dd> + <dt>{{jsxref("Number.parseInt()")}} {{experimental_inline}}</dt> + <dd>O valor é o mesmo que {{jsxref("Global_Objects/parseInt", "parseInt()")}} de um objecto global.</dd> +</dl> + +<h2 id="Instâncias_de_Number"><code>Instâncias de Number</code></h2> + +<p>Todas as instâncias de <code>Number </code>herdam de {{jsxref("Number.prototype")}}. O objecto protótipo (prototype) do constructor de <code>Number</code> pode ser modificado para afectar todas as instâncias de <code>Number</code>.</p> + +<h3 id="Métodos_2">Métodos</h3> + +<div>{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/prototype', 'Methods')}}</div> + +<h2 id="Exemplos">Exemplos</h2> + +<h3 id="Usar_o_objecto_Number_para_atribuír_valores_a_variáveis_numéricas">Usar o objecto <code>Number </code>para atribuír valores a variáveis numéricas</h3> + +<p>O seguinte exemplo usa as propriedades do objecto <code>Number</code> para atribuír valores a várias variáveis numéricas: </p> + +<pre class="brush: js">var biggestNum = Number.MAX_VALUE; +var smallestNum = Number.MIN_VALUE; +var infiniteNum = Number.POSITIVE_INFINITY; +var negInfiniteNum = Number.NEGATIVE_INFINITY; +var notANum = Number.NaN; +</pre> + +<h3 id="Limite_inteiro_para_Number"><code>Limite inteiro para Number</code></h3> + +<p>O seguinte exemplo mostra o mínimo e máximo valores inteiros que podem ser representados como um objecto <code>Number</code> (para mais detalhes, consulta o standard do ECMAScript, capítulo <em>8.5 The Number Type</em>):</p> + +<pre class="brush: js">var biggestInt = 9007199254740992; +var smallestInt = -9007199254740992; +</pre> + +<p>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 <code>Number</code>. Como possível alternativa, usa {{jsxref("String")}}.</p> + +<h3 id="Usar_Number_para_converter_um_objecto_Date">Usar <code>Number </code>para converter um objecto <code>Date</code></h3> + +<p>O seguinte exemplo converte o objecto {{jsxref("Date")}} num valor numérico usando <code>Number</code> como função:</p> + +<pre class="brush: js">var d = new Date('December 17, 1995 03:24:00'); +console.log(Number(d)); +</pre> + +<p>Este código imprime "819199440000".</p> + +<h3 id="Converter_strings_numéricas_para_números">Converter strings numéricas para números</h3> + +<pre class="brush: js">Number("123") // 123 +Number("") // 0 +Number("0x11") // 17 +Number("0b11") // 3 +Number("0o11") // 9 +Number("foo") // NaN +Number("100a") // NaN +</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Definição inicial. Implementado em JavaScript 1.1.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.7', 'Number')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-number-objects', 'Number')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>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")}})</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_dos_browsers">Compatibilidade dos browsers</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Funcionalidade</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Suporte básico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Funcionalidade</th> + <th>Android</th> + <th>Chrome para Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Suporte básico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li>{{jsxref("NaN")}}</li> + <li>The {{jsxref("Math")}} global object</li> +</ul> 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 new file mode 100644 index 0000000000..9b70ca6a98 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/global_objects/number/isfinite/index.html @@ -0,0 +1,126 @@ +--- +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 +--- +<div>{{JSRef}}</div> + +<p>O método <strong><code>Number.isFinite()</code></strong> determina se o valor passado é um número finito.</p> + +<h2 id="Sintaxe">Sintaxe</h2> + +<pre class="syntaxbox"><code>Number.isFinite(valor)</code></pre> + +<h3 id="Parâmetros">Parâmetros</h3> + +<dl> + <dt><code>valor</code></dt> + <dd>O valor a ser testado.</dd> +</dl> + +<h2 id="Descrição">Descrição</h2> + +<p>Em comparação com a função global {{jsxref("Global_Objects/isFinite", "isFinite()")}}, <strong><code>Number.isFinite()</code></strong> não converte forçosamente o parâmetro num number. Isto significa que apenas para valores do tipo number, finitos, retorna <code>true</code>.</p> + +<h2 id="Exemplos">Exemplos</h2> + +<pre class="brush: js">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') +</pre> + +<h2 id="Polyfill">Polyfill</h2> + +<pre class="brush: js">Number.isFinite = Number.isFinite || function(value) { + return typeof value === "number" && isFinite(value); +} +</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-number.isfinite', 'Number.isInteger')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_dos_browsers">Compatibilidade dos browsers</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Funcionalidade</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Suporte básico</td> + <td>{{CompatChrome("19")}}</td> + <td>{{CompatGeckoDesktop("16")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatOpera("15")}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Funcionalidade</th> + <th>Android</th> + <th>Chrome para Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Suporte básico</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile("16")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li>O objecto {{jsxref("Global_Objects/Number", "Number")}} ao qual pertence.</li> +</ul> 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 new file mode 100644 index 0000000000..8c6dc79bb7 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/global_objects/number/isinteger/index.html @@ -0,0 +1,125 @@ +--- +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 +--- +<div>{{JSRef}}</div> + +<p>O método <strong><code>Number.isInteger()</code></strong> determina se o valor passado é um inteiro.</p> + +<h2 id="Sintaxe">Sintaxe</h2> + +<pre class="syntaxbox"><code>Number.isInteger(valor)</code></pre> + +<h3 id="Parâmteros">Parâmteros</h3> + +<dl> + <dt><code>valor</code></dt> + <dd>O valor a ser testado por ser um inteiro.</dd> +</dl> + +<h2 id="Descrição">Descrição</h2> + +<p>Se o valor a ser testado for um inteiro, retorna <code>true</code>, senão retorna <code>false</code>. Se o valor for {{jsxref("Global_Objects/NaN", "NaN")}} ou infinito, retorna <code>false</code>.</p> + +<h2 id="Exemplos">Exemplos</h2> + +<pre class="brush: js">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 +</pre> + +<h2 id="Polyfill">Polyfill</h2> + +<pre class="brush: js">Number.isInteger = Number.isInteger || function(value) { + return typeof value === "number" && + isFinite(value) && + Math.floor(value) === value; +}; +</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-number.isinteger', 'Number.isInteger')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>Definição inicial.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_dos_browsers">Compatibilidade dos browsers</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Funcionalidade</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Suporte básico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("16")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Funcionalidade</th> + <th>Android</th> + <th>Chrome para Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Suporte básico</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatGeckoMobile("16")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li>O objecto {{jsxref("Global_Objects/Number", "Number")}} ao qual pertence.</li> +</ul> 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 new file mode 100644 index 0000000000..0b242adbbe --- /dev/null +++ b/files/pt-pt/web/javascript/reference/global_objects/number/isnan/index.html @@ -0,0 +1,136 @@ +--- +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 +--- +<div>{{JSRef}}</div> + +<p>O método <strong><code>Number.isNaN()</code></strong> determina se o valor passado é {{jsxref("Global_Objects/NaN", "NaN")}}. Esta é uma versão mais robusta que {{jsxref("Global_Objects/isNaN", "isNaN()")}}.</p> + +<h2 id="Sintaxe">Sintaxe</h2> + +<pre class="syntaxbox"><code>Number.isNaN(valor)</code></pre> + +<h3 id="Parâmetros">Parâmetros</h3> + +<dl> + <dt><code>valor</code></dt> + <dd>O valor a ser testado se é {{jsxref("Global_Objects/NaN", "NaN")}}.</dd> +</dl> + +<h2 id="Descrição">Descrição</h2> + +<p>Due to both equality operators, {{jsxref("Operators/Comparison_Operators", "==", "#Equality")}} and {{jsxref("Operators/Comparison_Operators", "===", "#Identity")}}, evaluating to <code>false</code> when checking if {{jsxref("Global_Objects/NaN", "NaN")}} <em>is</em> {{jsxref("Global_Objects/NaN", "NaN")}}, the function <code>Number.isNaN()</code> has become necessary. This situation is unlike all other possible value comparisons in JavaScript.</p> + +<p>In comparison to the global {{jsxref("Global_Objects/isNaN", "isNaN()")}} function, <code>Number.isNaN()</code> 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 <code>true</code>.</p> + +<h2 id="Exemplos">Exemplos</h2> + +<pre class="brush: js">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(" "); +</pre> + +<h2 id="Polyfill">Polyfill</h2> + +<pre class="brush: js">Number.isNaN = Number.isNaN || function(value) { + return typeof value === "number" && isNaN(value); +}</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-number.isnan', 'Number.isnan')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>Definição inicial.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_dos_browsers">Compatibilidade dos browsers</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Funcionalidade</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatChrome("25")}}</td> + <td>{{CompatGeckoDesktop("15")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>9</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Funcionalidade</th> + <th>Android</th> + <th>Chrome para Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile("15")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>iOS 9+</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li>{{jsxref("Global_Objects/Number", "Number")}}</li> + <li>{{jsxref("Global_Objects/isNaN", "isNaN()")}}</li> +</ul> 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 new file mode 100644 index 0000000000..cd1666ecbc --- /dev/null +++ b/files/pt-pt/web/javascript/reference/global_objects/number/max_value/index.html @@ -0,0 +1,119 @@ +--- +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 +--- +<div>{{JSRef}}</div> + +<p>A propriedade <strong><code>Number.MAX_VALUE </code></strong>representa o máximo valor numérico representável em JavaScript.</p> + +<div>{{js_property_attributes(0, 0, 0)}}</div> + +<h2 id="Descrição">Descrição</h2> + +<p>A propriedade <code>MAX_VALUE</code> tem um valor aproximado de <code>1.79E+308</code>. Valores maiores do que <code>MAX_VALUE</code> são representados como "<code>Infinity</code>".</p> + +<p>Dado que <code>MAX_VALUE</code> é uma propriedade estática (static) de {{jsxref("Number")}}, tu deves sempre usá-la na forma <code>Number.MAX_VALUE</code>, em vez de na forma de uma propriedade de um objecto {{jsxref("Number")}} que tenhas criado.</p> + +<h2 id="Exemplos">Exemplos</h2> + +<h3 id="Usando_MAX_VALUE">Usando <code>MAX_VALUE</code></h3> + +<p>O seguinte código multiplica dois valores numéricos. Se o resultado for inferior ou igual a <code>MAX_VALUE</code>, a função <code>func1</code> é chamada; senão será chamada a função <code>func2</code>.</p> + +<pre class="brush: js">if (num1 * num2 <= Number.MAX_VALUE) { + func1(); +} else { + func2(); +} +</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Definição inicial. Implementado em JavaScript 1.1.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.7.3.2', 'Number.MAX_VALUE')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-number.max_value', 'Number.MAX_VALUE')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_dos_browsers">Compatibilidade dos browsers</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Funcionalidade</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Suporte básico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Funcionalidade</th> + <th>Android</th> + <th>Chrome para Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Suporte básico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li>{{jsxref("Number.MIN_VALUE")}}</li> +</ul> 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 new file mode 100644 index 0000000000..852b37426b --- /dev/null +++ b/files/pt-pt/web/javascript/reference/global_objects/number/min_value/index.html @@ -0,0 +1,121 @@ +--- +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 +--- +<div>{{JSRef}}</div> + +<p>A propriedade <strong><code>Number.MIN_VALUE </code></strong>representa o mínimo valor numérico representável em JavaScript.</p> + +<div>{{js_property_attributes(0, 0, 0)}}</div> + +<h2 id="Descrição">Descrição</h2> + +<p>A propriedade <code>MIN_VALUE</code> representa o valor mais próximo de 0 (zero), não negativo, que o JavaScript consegue representar.</p> + +<p>A propriedade <code>MIN_VALUE</code> tem um valor aproximado de <code>5e-324</code>. Valores menores do que <code>MIN_VALUE </code>("underflow values") são são convertidos para 0 (zero).</p> + +<p>Dado que <code>MIN_VALUE</code> é uma propriedade estática (static) de {{jsxref("Number")}}, tu deves sempre usá-la na forma <code>Number.MIN_VALUE</code>, em vez de na forma de uma propriedade de um objecto {{jsxref("Number")}} que tenhas criado.</p> + +<h2 id="Exemplos">Exemplos</h2> + +<h3 id="Usando_MIN_VALUE">Usando <code>MIN_VALUE</code></h3> + +<p>O seguinte código divide dois valores numéricos. Se o resultado for superior ou igual a <code>MIN_VALUE</code>, a função <code>func1</code> é chamada; senão será chamada a função <code>func2</code>.</p> + +<pre class="brush: js">if (num1 / num2 >= Number.MIN_VALUE) { + func1(); +} else { + func2(); +} +</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.1.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.7.3.3', 'Number.MIN_VALUE')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-number.min_value', 'Number.MIN_VALUE')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_dos_browsers">Compatibilidade dos browsers</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Funcionalidade</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Suporte básico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Funcionalidade</th> + <th>Android</th> + <th>Chrome para Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Suporte básico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li>{{jsxref("Number.MAX_VALUE")}}</li> +</ul> 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 new file mode 100644 index 0000000000..c3213486b7 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/global_objects/number/nan/index.html @@ -0,0 +1,103 @@ +--- +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 +--- +<div>{{JSRef}}</div> + +<p>A propriedade <strong><code>Number.NaN </code></strong>representa um Não-Número. Equivalente a {{jsxref("NaN")}}.</p> + +<p>Não precisas de criar um objecto {{jsxref("Number")}} para aceder a esta propriedade estática (static) (usa <code>Number.NaN</code>).</p> + +<div>{{js_property_attributes(0, 0, 0)}}</div> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Definição inicial. Implementado no JavaScript 1.1.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.7.3.4', 'Number.NaN')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-number.nan', 'Number.NaN')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_dos_browsers">Compatibilidade dos browsers</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Funcionalidade</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Suporte básico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Funcionalidade</th> + <th>Android</th> + <th>Chrome para Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Suporte básico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li>O objecto global {{jsxref("NaN")}}.</li> + <li>O objecto {{jsxref("Number")}} ao qual pertence.</li> +</ul> 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 new file mode 100644 index 0000000000..a2a7d0f962 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/global_objects/number/negative_infinity/index.html @@ -0,0 +1,91 @@ +--- +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 +--- +<div>{{JSRef}}</div> + +<p>A propriedade <strong><code>Number.NEGATIVE_INFINITY</code></strong> representa o valor negativo Infinito.</p> + +<p>Não tem de criar um objecto {{jsxref("Number")}} para aceder a esta propriedade estática (usa <code>Number.NEGATIVE_INFINITY</code>).</p> + +<div>{{js_property_attributes(0, 0, 0)}}</div> + +<h2 id="Descrição">Descrição</h2> + +<p>O valor de <code>Number.NEGATIVE_INFINITY</code> é o mesmo que o valor negativo da propriedade {{jsxref("Infinity")}} do objeto global.</p> + +<p>Este valor comporta-se de forma ligeiramente diferente do infinito matemático:</p> + +<ul> + <li>Qualquer valor positivo, incluindo {{jsxref("Number.POSITIVE_INFINITY", "POSITIVE_INFINITY")}}, multiplicado por <code>NEGATIVE_INFINITY</code> é igual a <code>NEGATIVE_INFINITY</code>.</li> + <li>Qualquer valor negativo, incluindo,<code>NEGATIVE_INFINITY</code> multiplicado por <code>NEGATIVE_INFINITY</code> é igual a {{jsxref("Number.POSITIVE_INFINITY", "POSITIVE_INFINITY")}}.</li> + <li>O valor 0 (zero) multiplicado por <code>NEGATIVE_INFINITY</code> é igual a {{jsxref("NaN")}}.</li> + <li>{{jsxref("NaN")}} multiplicado por <code>NEGATIVE_INFINITY</code> é igual a {{jsxref("NaN")}}.</li> + <li><code>NEGATIVE_INFINITY</code>, dividido por qualquer valor negativo excepto <code>NEGATIVE_INFINITY</code>, é igual a {{jsxref("Number.POSITIVE_INFINITY", "POSITIVE_INFINITY")}}.</li> + <li><code>NEGATIVE_INFINITY</code>, dividido por qualquer valor positivo exceto {{jsxref("Number.POSITIVE_INFINITY", "POSITIVE_INFINITY")}}, é igual a <code>NEGATIVE_INFINITY</code>.</li> + <li><code>NEGATIVE_INFINITY</code>, dividido por outro <code>NEGATIVE_INFINITY</code> ou {{jsxref("Number.POSITIVE_INFINITY", "POSITIVE_INFINITY")}}, é igual a {{jsxref("NaN")}}.</li> + <li>Qualquer número dividido por <code>NEGATIVE_INFINITY</code> é igual a 0 (zero).</li> +</ul> + +<p>Pode usar a propriedade <code>Number.NEGATIVE_INFINITY</code> para indicar uma condição de erro numa situação em que, no caso de sucesso, é retornado um valor finito.</p> + +<h2 id="Exemplos">Exemplos</h2> + +<h3 id="Usando_NEGATIVE_INFINITY">Usando <code>NEGATIVE_INFINITY</code></h3> + +<p>No seguinte exemplo, é atribuído à variável <code>smallNumber</code> um valor inferior ao valor mínimo. Quando a linha de código {{jsxref("Statements/if...else", "if")}} é executada, a variável <code>smallNumber</code> tem o valor <code>-Infinity</code>, então é atribuída à mesma variável um valor finito antes de continuar.</p> + +<pre class="brush: js notranslate">var smallNumber = (-Number.MAX_VALUE) * 2; + +if (smallNumber == Number.NEGATIVE_INFINITY) { + smallNumber = returnFinite(); +} +</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.1.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.7.3.5', 'Number.NEGATIVE_INFINITY')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-number.negative_infinity', 'Number.NEGATIVE_INFINITY')}}</td> + <td>{{Spec2('ES6')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade">Compatibilidade</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.Number.NEGATIVE_INFINITY")}}</p> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li>{{jsxref("Number.POSITIVE_INFINITY")}}</li> + <li>{{jsxref("Number.isFinite()")}}</li> + <li>{{jsxref("Global_Objects/Infinity", "Infinity")}}</li> + <li>{{jsxref("Global_Objects/isFinite", "isFinite()")}}</li> +</ul> diff --git a/files/pt-pt/web/javascript/reference/global_objects/number/prototype/index.html b/files/pt-pt/web/javascript/reference/global_objects/number/prototype/index.html new file mode 100644 index 0000000000..7bd7fb8739 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/global_objects/number/prototype/index.html @@ -0,0 +1,130 @@ +--- +title: Number.prototype +slug: Web/JavaScript/Reference/Global_Objects/Number/prototype +tags: + - JavaScript + - Number + - Property + - Prototype +translation_of: Web/JavaScript/Reference/Global_Objects/Number +--- +<div>{{JSRef}}</div> + +<p>A propriedade <strong><code>Number.prototype</code></strong> representa o protótipo (prototype) para o constructor de {{jsxref("Number")}}.</p> + +<div>{{js_property_attributes(0, 0, 0)}}</div> + +<h2 id="Descrição">Descrição</h2> + +<p>Todas as instâncias de {{jsxref("Number")}} herdam de <code>Number.prototype</code>. O objecto protótipo (prototype) do constructor de {{jsxref("Number")}} pode ser modificado para afectar todas as instâncias de {{jsxref( "Number")}}.</p> + +<h2 id="Propriedades">Propriedades</h2> + +<dl> + <dt><code>Number.prototype.constructor</code></dt> + <dd>Retorna a função criadora das instâncias deste objecto. Por predifinição este é o objecto {{jsxref("Number")}}.</dd> +</dl> + +<h2 id="Métodos">Métodos</h2> + +<dl> + <dt>{{jsxref("Number.prototype.toExponential()")}}</dt> + <dd>Retorna uma representação em string do número em notação científica.</dd> + <dt>{{jsxref("Number.prototype.toFixed()")}}</dt> + <dd>Retorna uma representação em string do número em notação de ponto fixo.</dd> + <dt>{{jsxref("Number.prototype.toLocaleString()")}}</dt> + <dd>Retorna uma string do número numa representação sensível à linguagem. Faz override do método {{jsxref("Object.prototype.toLocaleString()")}}.</dd> + <dt>{{jsxref("Number.prototype.toPrecision()")}}</dt> + <dd>Retorna uma representação em string do número numa precisão especificada em ponto fixo ou notação científica.</dd> + <dt>{{jsxref("Number.prototype.toSource()")}} {{non-standard_inline}}</dt> + <dd>Retorna um objecto literal representando o objecto {{jsxref("Number")}} especificado; podes usar este valor para criar um novo objecto. Faz override ao método {{jsxref("Object.prototype.toSource()")}}.</dd> + <dt>{{jsxref("Number.prototype.toString()")}}</dt> + <dd>Retorna uma representação em string do objecto especificado na base especificada. Faz override ao método {{jsxref("Object.prototype.toString()")}}.</dd> + <dt>{{jsxref("Number.prototype.valueOf()")}}</dt> + <dd>Retorna o valor primitivo do objecto especificado. Faz override ao método {{jsxref("Object.prototype.valueOf()")}}.</dd> +</dl> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Definição Inicial. Implementado em JavaScript 1.1.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.7.4', 'Number')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-properties-of-the-number-prototype-object', 'Number')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_dos_browsers">Compatibilidade dos browsers</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Funcionalidade</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Suporte básico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Funcionalidade</th> + <th>Android</th> + <th>Chrome para Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Suporte básico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li>{{jsxref("Number")}}</li> +</ul> 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 new file mode 100644 index 0000000000..1ff4892314 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/global_objects/number/tostring/index.html @@ -0,0 +1,146 @@ +--- +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 +--- +<div>{{JSRef}}</div> + +<p>O método <strong><code>toString()</code></strong> retorna uma string com o valor do objecto {{jsxref("Number")}} especificado.</p> + +<h2 id="Sintaxe">Sintaxe</h2> + +<pre class="syntaxbox"><code><var>numObj</var>.toString([<var>radix</var>])</code></pre> + +<h3 id="Parâmetros">Parâmetros</h3> + +<dl> + <dt><code>base</code></dt> + <dd>Opcional. Um inteiro entre [2, 36] especificando a base usada para representar o valor númerico.</dd> +</dl> + +<h3 id="Erros_possíveis">Erros possíveis</h3> + +<dl> + <dt>{{jsxref("RangeError")}}</dt> + <dd>Se o valor do parâmetro base não estiver entre [2, 36], o erro {{jsxref("RangeError")}} é lançado.</dd> +</dl> + +<h2 id="Descrição">Descrição</h2> + +<p>O objecto {{jsxref("Number")}} faz override ao método <code>toString()</code> do objecto {{jsxref("Object")}}; não herda de {{jsxref("Object.prototype.toString()")}}. Para os objectos {{jsxref( "Number")}}, o método <code>toString() </code>retorna uma representação em string do ojecto na base especificada.</p> + +<p>O método <code>toString() </code>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é <code>f</code>.</p> + +<p>Se a <code>base </code>não for especificada, o seu valor assumido é 10.</p> + +<p>Se o <code><var>numObj </var></code>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 <code><var>numObj </var></code>precedida pelo sinal negativo (-), e não complement para 2 de <code>numObj</code>.</p> + +<h2 id="Exemplos">Exemplos</h2> + +<h3 id="Usando_toString">Usando <code>toString</code></h3> + +<pre class="brush: js">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' +</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Definição inicial. Implementado em JavaScript 1.1.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.7.4.2', 'Number.prototype.tostring')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-number.prototype.tostring', 'Number.prototype.tostring')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_dos_browsers">Compatibilidade dos browsers</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Funcionalidade</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Suporte básico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Funcionalidade</th> + <th>Android</th> + <th>Chrome para Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>BSuporte básico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li>{{jsxref("Number.prototype.toFixed()")}}</li> + <li>{{jsxref("Number.prototype.toExponential()")}}</li> + <li>{{jsxref("Number.prototype.toPrecision()")}}</li> +</ul> 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 new file mode 100644 index 0000000000..2c91823404 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/global_objects/object/hasownproperty/index.html @@ -0,0 +1,187 @@ +--- +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 +--- +<div>{{JSRef}}</div> + +<p>O método <code><strong>hasOwnProperty()</strong></code> retorna um booleano indicando se o objeto tem a propriedade especificada.</p> + +<h2 id="Sintaxe">Sintaxe</h2> + +<pre class="syntaxbox"><code><var>obj</var>.hasOwnProperty(<var>prop</var>)</code></pre> + +<h3 id="Parâmetros">Parâmetros</h3> + +<dl> + <dt><code>prop</code></dt> + <dd>O nome da propriedade para testar.</dd> +</dl> + +<h2 id="Descrição">Descrição</h2> + +<p>Cada objecto descendente de {{jsxref("Object")}} herda o método <code>hasOwnProperty</code>. 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.</p> + +<h2 id="Exemplos">Exemplos</h2> + +<h3 id="Usando_hasOwnProperty_para_testar_a_existência_de_uma_propriedade">Usando <code>hasOwnProperty</code> para testar a existência de uma propriedade</h3> + +<p>O seguinte exemplo determina se o objecto "o" contém a propriedade "<code>prop"</code>:</p> + +<pre class="brush: js">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 +</pre> + +<h3 id="Direto_versus_propriedades_herdadas">Direto versus propriedades herdadas</h3> + +<p>O seguinte exemplo diferencia entre propriedades diretas e propriedades herdadas através da cadeia de protótipos:</p> + +<pre class="brush: js">o = new Object(); +o.prop = 'existe'; +o.hasOwnProperty('prop'); // retorna true +o.hasOwnProperty('toString'); // retorna false +o.hasOwnProperty('hasOwnProperty'); // retorna false +</pre> + +<h3 id="Iteração_entre_as_propriedades_de_um_objeto">Iteração entre as propriedades de um objeto</h3> + +<p>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 <code>hasOwnProperty</code> em si é estritamente limitado aos itens enumeráveis (como com {{jsxref("Object.getOwnPropertyNames()")}}).</p> + +<pre class="brush: js">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 + } +} +</pre> + +<h3 id="Usando_hasOwnProperty_como_um_nome_de_uma_propriedade">Usando <code>hasOwnProperty</code> como um nome de uma propriedade</h3> + +<p>JavaScript não protege a propriedade <code>hasOwnProperty</code>; assim, se a possibilidade existe de um objeto poder ter uma propriedade com este nome, é necessário usar um <code>hasOwnProperty</code> externo para obter resultados corretos:</p> + +<pre class="brush: js">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 +</pre> + +<p>Note que no último caso, não há objetos recém-criados.</p> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + <tr> + <td>{{SpecName('ES3')}}</td> + <td>{{Spec2('ES3')}}</td> + <td>Definição inicial. Implementado em JavaScript 1.5.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.2.4.5', 'Object.prototype.hasOwnProperty')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-object.prototype.hasownproperty', 'Object.prototype.hasOwnProperty')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_entre_browsers">Compatibilidade entre browsers</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Suporte básico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Android</th> + <th>Chrome para Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Suporte básico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Veja_também">Veja também</h2> + +<ul> + <li><a href="/en-US/docs/Enumerability_and_ownership_of_properties">Enumerabilidade e posse de propriedades</a></li> + <li>{{jsxref("Object.getOwnPropertyNames()")}}</li> + <li>{{jsxref("Statements/for...in", "for...in")}}</li> + <li>{{jsxref("Operators/in", "in")}}</li> + <li><a href="/en-US/docs/Web/JavaScript/Guide/Inheritance_Revisited">Guia JavaScript: Herança e a cadeia de protótipos</a></li> +</ul> 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 new file mode 100644 index 0000000000..e393f833b8 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/global_objects/object/index.html @@ -0,0 +1,184 @@ +--- +title: Object +slug: Web/JavaScript/Reference/Global_Objects/Object +tags: + - Constructor + - Construtor + - JavaScript + - Object + - Objeto +translation_of: Web/JavaScript/Reference/Global_Objects/Object +--- +<div>{{JSRef}}</div> + +<p>o construtor <code><strong>Object</strong></code> cria um wrapper de objeto.</p> + +<h2 id="Sintaxe">Sintaxe</h2> + +<pre class="syntaxbox">// Object initialiser or literal +{ [ <var>nameValuePair1</var>[, <var>nameValuePair2</var>[, ...<var>nameValuePairN</var>] ] ] } + +// Called as a constructor +new Object([<var>value</var>])</pre> + +<h3 id="Parâmetros">Parâmetros</h3> + +<dl> + <dt><code>nameValuePair1, nameValuePair2, ... nameValuePair<em>N</em></code></dt> + <dd>Pairs of names (strings) and values (any value) where the name is separated from the value by a colon.</dd> + <dt><code>value</code></dt> + <dd>Any value.</dd> +</dl> + +<h2 id="Descrição">Descrição</h2> + +<p>The <code>Object</code> 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.</p> + +<p>When called in a non-constructor context, <code>Object</code> behaves identically to <code>new Object()</code>.</p> + +<p>See also the <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer">object initializer / literal syntax</a>.</p> + +<h2 id="Propriedades_de_um_construtor_Object">Propriedades de um construtor <code>Object</code></h2> + +<dl> + <dt><code>Object.length</code></dt> + <dd>Tem um valor de 1.</dd> + <dt>{{jsxref("Object.prototype")}}</dt> + <dd>Permite a adição de propriedades para todos os objetos do tipo <em>Object</em>.</dd> +</dl> + +<h2 id="Métodos_de_um_construtor_Object">Métodos de um construtor <code>Object</code></h2> + +<dl> + <dt>{{jsxref("Object.assign()")}}</dt> + <dd>Copies the values of all enumerable own properties from one or more source objects to a target object.</dd> + <dt>{{jsxref("Object.create()")}}</dt> + <dd>Creates a new object with the specified prototype object and properties.</dd> + <dt>{{jsxref("Object.defineProperty()")}}</dt> + <dd>Adds the named property described by a given descriptor to an object.</dd> + <dt>{{jsxref("Object.defineProperties()")}}</dt> + <dd>Adds the named properties described by the given descriptors to an object.</dd> + <dt>{{jsxref("Object.entries()")}}</dt> + <dd>Returns an array containing all of the <code>[key, value]</code> pairs of a given object's <strong>own</strong> enumerable string properties.</dd> + <dt>{{jsxref("Object.freeze()")}}</dt> + <dd>Freezes an object: other code can't delete or change any properties.</dd> + <dt>{{jsxref("Object.fromEntries()")}}</dt> + <dd>Returns a new object from an iterable of key-value pairs (reverses {{jsxref("Object.entries")}}).</dd> + <dt>{{jsxref("Object.getOwnPropertyDescriptor()")}}</dt> + <dd>Returns a property descriptor for a named property on an object.</dd> + <dt>{{jsxref("Object.getOwnPropertyDescriptors()")}}</dt> + <dd>Returns an object containing all own property descriptors for an object.</dd> + <dt>{{jsxref("Object.getOwnPropertyNames()")}}</dt> + <dd>Returns an array containing the names of all of the given object's <strong>own</strong> enumerable and non-enumerable properties.</dd> + <dt>{{jsxref("Object.getOwnPropertySymbols()")}}</dt> + <dd>Returns an array of all symbol properties found directly upon a given object.</dd> + <dt>{{jsxref("Object.getPrototypeOf()")}}</dt> + <dd>Returns the prototype of the specified object.</dd> + <dt>{{jsxref("Object.is()")}}</dt> + <dd>Compares if two values are the same value. Equates all NaN values (which differs from both Abstract Equality Comparison and Strict Equality Comparison).</dd> + <dt>{{jsxref("Object.isExtensible()")}}</dt> + <dd>Determines if extending of an object is allowed.</dd> + <dt>{{jsxref("Object.isFrozen()")}}</dt> + <dd>Determines if an object was frozen.</dd> + <dt>{{jsxref("Object.isSealed()")}}</dt> + <dd>Determines if an object is sealed.</dd> + <dt>{{jsxref("Object.keys()")}}</dt> + <dd>Returns an array containing the names of all of the given object's <strong>own</strong> enumerable string properties.</dd> + <dt>{{jsxref("Object.preventExtensions()")}}</dt> + <dd>Prevents any extensions of an object.</dd> + <dt>{{jsxref("Object.seal()")}}</dt> + <dd>Prevents other code from deleting properties of an object.</dd> + <dt>{{jsxref("Object.setPrototypeOf()")}}</dt> + <dd>Sets the prototype (i.e., the internal <code>[[Prototype]]</code> property).</dd> + <dt>{{jsxref("Object.values()")}}</dt> + <dd>Returns an array containing the values that correspond to all of a given object's <strong>own</strong> enumerable string properties.</dd> +</dl> + +<h2 id="Instâcias_de_Object_e_objeto_protótipo_Object">Instâcias de <code>Object</code> e objeto protótipo <code>Object</code></h2> + +<p>All objects in JavaScript are descended from <code>Object</code>; all objects inherit methods and properties from {{jsxref("Object.prototype")}}, although they may be overridden. For example, other constructors' prototypes override the <code>constructor</code> property and provide their own <code>toString()</code> methods. Changes to the <code>Object</code> prototype object are propagated to all objects unless the properties and methods subject to those changes are overridden further along the prototype chain.</p> + +<h3 id="Propriedades">Propriedades</h3> + +<div>{{page('//pt-PT/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype', 'Propriedades') }}</div> + +<h3 id="Métodos">Métodos</h3> + +<div>{{page('//pt-PT/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype', 'Métodos') }}</div> + +<h2 id="Deleting_a_property_from_an_object">Deleting a property from an object</h2> + +<p>There isn't any method in an Object itself to delete its own properties (e.g. like <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/delete">Map.prototype.delete()</a></code>). To do so one has to use the <a href="/en-US/docs/Web/JavaScript/Reference/Operators/delete">delete operator</a>.</p> + +<h2 id="Exemplos">Exemplos</h2> + +<h3 id="Using_Object_given_undefined_and_null_types">Using <code>Object</code> given <code>undefined</code> and <code>null</code> types</h3> + +<p>The following examples store an empty <code>Object</code> object in <code>o</code>:</p> + +<pre class="brush: js">var o = new Object(); +</pre> + +<pre class="brush: js">var o = new Object(undefined); +</pre> + +<pre class="brush: js">var o = new Object(null); +</pre> + +<h3 id="Using_Object_to_create_Boolean_objects">Using <code>Object</code> to create <code>Boolean</code> objects</h3> + +<p>The following examples store {{jsxref("Boolean")}} objects in <code>o</code>:</p> + +<pre class="brush: js">// equivalent to o = new Boolean(true); +var o = new Object(true); +</pre> + +<pre class="brush: js">// equivalent to o = new Boolean(false); +var o = new Object(Boolean()); +</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.0.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.2', 'Object')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-object-objects', 'Object')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>Added Object.assign, Object.getOwnPropertySymbols, Object.setPrototypeOf, Object.is</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-object-objects', 'Object')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td>Added Object.entries, Object.values and Object.getOwnPropertyDescriptors.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_de_navegador">Compatibilidade de navegador</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Object")}}</p> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/pt-PT/docs/Web/JavaScript/Reference/Operadores/Inicializador_objeto">Inicializador de objeto</a></li> +</ul> diff --git a/files/pt-pt/web/javascript/reference/global_objects/object/prototype/index.html b/files/pt-pt/web/javascript/reference/global_objects/object/prototype/index.html new file mode 100644 index 0000000000..c98a57ec52 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/global_objects/object/prototype/index.html @@ -0,0 +1,198 @@ +--- +title: Object.prototype +slug: Web/JavaScript/Reference/Global_Objects/Object/prototype +tags: + - JavaScript + - Object + - Objeto + - Propriedade +translation_of: Web/JavaScript/Reference/Global_Objects/Object +--- +<div>{{JSRef}}</div> + +<p>A propriedade <code><strong>Object.prototype</strong></code> representa o <em>prototype object</em> {{jsxref("Object","Objeto")}} .</p> + +<div>{{js_property_attributes(0, 0, 0)}}</div> + +<h2 id="Descrição">Descrição</h2> + +<p>Nearly all objects in JavaScript are instances of {{jsxref("Object")}}; a typical object inherits properties (including methods) from <code>Object.prototype</code>, although these properties may be shadowed (a.k.a. overridden). However, an <code>Object</code> may be deliberately created for which this is not true (e.g. by {{jsxref("Object.create", "Object.create(null)")}}), or it may be altered so that this is no longer true (e.g. with {{jsxref("Object.setPrototypeOf")}}).</p> + +<p>Changes to the <code>Object</code> prototype object are seen by <strong>all</strong> objects through prototype chaining, unless the properties and methods subject to those changes are overridden further along the prototype chain. This provides a very powerful although potentially dangerous mechanism to override or extend object behavior.</p> + +<h2 id="Propriedades">Propriedades</h2> + +<dl> + <dt>{{jsxref("Object.prototype.constructor")}}</dt> + <dd>Specifies the function that creates an object's prototype.</dd> + <dt>{{jsxref("Object.prototype.__proto__")}} {{non-standard_inline}}</dt> + <dd>Points to the object which was used as prototype when the object was instantiated.</dd> + <dt>{{jsxref("Object.prototype.__noSuchMethod__")}} {{non-standard_inline}}</dt> + <dd>Allows a function to be defined that will be executed when an undefined object member is called as a method.</dd> + <dt><s class="obsoleteElement">{{jsxref("Object.prototype.count","Object.prototype.__count__")}} {{obsolete_inline}}</s></dt> + <dd><s class="obsoleteElement">Used to return the number of enumerable properties directly on a user-defined object, but has been removed.</s></dd> + <dt><s class="obsoleteElement">{{jsxref("Object.prototype.parent","Object.prototype.__parent__")}} {{obsolete_inline}}</s></dt> + <dd><s class="obsoleteElement">Used to point to an object's context, but has been removed.</s></dd> +</dl> + +<h2 id="Métodos">Métodos</h2> + +<dl> + <dt>{{jsxref("Object.prototype.__defineGetter__()")}} {{non-standard_inline}} {{deprecated_inline}}</dt> + <dd>Associates a function with a property that, when accessed, executes that function and returns its return value.</dd> + <dt>{{jsxref("Object.prototype.__defineSetter__()")}} {{non-standard_inline}} {{deprecated_inline}}</dt> + <dd>Associates a function with a property that, when set, executes that function which modifies the property.</dd> + <dt>{{jsxref("Object.prototype.__lookupGetter__()")}} {{non-standard_inline}} {{deprecated_inline}}</dt> + <dd>Returns the function associated with the specified property by the {{jsxref("Object.prototype.__defineGetter__()", "__defineGetter__()")}} method.</dd> + <dt>{{jsxref("Object.prototype.__lookupSetter__()")}} {{non-standard_inline}} {{deprecated_inline}}</dt> + <dd>Returns the function associated with the specified property by the {{jsxref("Object.prototype.__defineSetter__()", "__defineSetter__()")}} method.</dd> + <dt>{{jsxref("Object.prototype.hasOwnProperty()")}}</dt> + <dd>Returns a boolean indicating whether an object contains the specified property as a direct property of that object and not inherited through the prototype chain.</dd> + <dt>{{jsxref("Object.prototype.isPrototypeOf()")}}</dt> + <dd>Returns a boolean indicating whether the object this method is called upon is in the prototype chain of the specified object.</dd> + <dt>{{jsxref("Object.prototype.propertyIsEnumerable()")}}</dt> + <dd>Returns a boolean indicating if the internal <a href="/en-US/docs/Web/JavaScript/Data_structures#Properties">ECMAScript [[Enumerable]] attribute</a> is set.</dd> + <dt>{{jsxref("Object.prototype.toSource()")}} {{non-standard_inline}}</dt> + <dd>Returns string containing the source of an object literal representing the object that this method is called upon; you can use this value to create a new object.</dd> + <dt>{{jsxref("Object.prototype.toLocaleString()")}}</dt> + <dd>Calls {{jsxref("Object.toString", "toString()")}}.</dd> + <dt>{{jsxref("Object.prototype.toString()")}}</dt> + <dd>Returns a string representation of the object.</dd> + <dt>{{jsxref("Object.prototype.unwatch()")}} {{non-standard_inline}}</dt> + <dd>Removes a watchpoint from a property of the object.</dd> + <dt>{{jsxref("Object.prototype.valueOf()")}}</dt> + <dd>Returns the primitive value of the specified object.</dd> + <dt>{{jsxref("Object.prototype.watch()")}} {{non-standard_inline}}</dt> + <dd>Adds a watchpoint to a property of the object.</dd> + <dt><s class="obsoleteElement">{{jsxref("Object.prototype.eval()")}} {{obsolete_inline}}</s></dt> + <dd><s class="obsoleteElement">Used to evaluate a string of JavaScript code in the context of the specified object, but has been removed.</s></dd> +</dl> + +<h2 id="Exemplos">Exemplos</h2> + +<p>When altering the behavior of existing Object.prototype methods, consider injecting code by wrapping your extension before or after the existing logic. For example, this (untested) code will pre-conditionally execute custom logic before the built-in logic or someone else's extension is executed.</p> + +<p>When a function is called, the arguments to the call are held in the array-like "variable" <a href="/en-US/docs/Web/JavaScript/Reference/Functions/arguments">arguments</a>. For example, in the call "myFn(a, b, c)", the arguments within myFn's body will contain 3 array-like elements corresponding to (a, b, c). When modifying prototypes with hooks, simply pass this & the arguments (the call state) to the current behavior by calling apply() on the function. This pattern can be used for any prototype, such as Node.prototype, Function.prototype, etc.</p> + +<pre class="brush: js">var current = Object.prototype.valueOf; + +// Since my property "-prop-value" is cross-cutting and isn't always +// on the same prototype chain, I want to modify Object.prototype: +Object.prototype.valueOf = function() { + if (this.hasOwnProperty('-prop-value')) { + return this['-prop-value']; + } else { + // It doesn't look like one of my objects, so let's fall back on + // the default behavior by reproducing the current behavior as best we can. + // The apply behaves like "super" in some other languages. + // Even though valueOf() doesn't take arguments, some other hook may. + return current.apply(this, arguments); + } +} +</pre> + +<p>Since JavaScript doesn't exactly have sub-class objects, prototype is a useful workaround to make a “base class” object of certain functions that act as objects. For example:</p> + +<pre class="brush: js">var Person = function(name) { + this.name = name; + this.canTalk = true; +}; + +Person.prototype.greet = function() { + if (this.canTalk) { + console.log('Hi, I am ' + this.name); + } +}; + +var Employee = function(name, title) { + Person.call(this, name); + this.title = title; +}; + +Employee.prototype = Object.create(Person.prototype); + +Employee.prototype.greet = function() { + if (this.canTalk) { + console.log('Hi, I am ' + this.name + ', the ' + this.title); + } +}; + +var Customer = function(name) { + Person.call(this, name); +}; + +Customer.prototype = Object.create(Person.prototype); + +var Mime = function(name) { + Person.call(this, name); + this.canTalk = false; +}; + +Mime.prototype = Object.create(Person.prototype); + +var bob = new Employee('Bob', 'Builder'); +var joe = new Customer('Joe'); +var rg = new Employee('Red Green', 'Handyman'); +var mike = new Customer('Mike'); +var mime = new Mime('Mime'); + +bob.greet(); +// Hi, I am Bob, the Builder + +joe.greet(); +// Hi, I am Joe + +rg.greet(); +// Hi, I am Red Green, the Handyman + +mike.greet(); +// Hi, I am Mike + +mime.greet(); +</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.0.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.2.3.1', 'Object.prototype')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-object.prototype', 'Object.prototype')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-object.prototype', 'Object.prototype')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_de_navegador">Compatibilidade de navegador</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Object.prototype")}}</p> +</div> + +<h2 id="Consultar_também">Consultar também</h2> + +<ul> + <li><a href="/pt-PT/docs/Learn/JavaScript/Objects">Introdução ao JavaScript Orientado a Objetos</a></li> +</ul> 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 new file mode 100644 index 0000000000..4ccc8f5f81 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/global_objects/string/index.html @@ -0,0 +1,326 @@ +--- +title: String +slug: Web/JavaScript/Reference/Global_Objects/String +tags: + - ECMAScript 2015 + - JavaScript + - Referencia + - String +translation_of: Web/JavaScript/Reference/Global_Objects/String +--- +<div>{{JSRef}}</div> + +<p>O objeto global <strong><code>String</code></strong> é um construtor de <em>strings</em> ou sequência de carateres.</p> + +<h2 id="Sintaxe">Sintaxe</h2> + +<p>Os literais de string assumem as formas:</p> + +<pre class="syntaxbox"><code>'string text' +"string text" +"中文 español English हिन्दी العربية português বাংলা русский 日本語 ਪੰਜਾਬੀ 한국어 தமிழ்"</code></pre> + +<p>As Strings podem também ser criadas usando o objecto global string directamente:</p> + +<pre class="syntaxbox"><code>String(thing) +new String(thing)</code></pre> + +<h3 id="Parâmetros">Parâmetros</h3> + +<dl> + <dt><code>thing</code></dt> + <dd>Qualquer parâmetro para ser convertido numa <em>string</em>.</dd> +</dl> + +<h3 id="Strings_modelo"><em>Strings </em>modelo</h3> + +<p>A partir de ECMAScript 2015, os literais de <em>strings</em> podem também ser chamados de <a href="/en-US/docs/Web/JavaScript/Reference/template_strings">Modelo strings</a>:</p> + +<pre class="brush: js"><code>`hello world`</code> +`hello! + world!` +<code>`hello ${who}`</code> +<code>escape `<a>${who}</a>`</code></pre> + +<dl> +</dl> + +<h3 id="Notação_Escape">Notação <em>Escape</em></h3> + +<p>Além dos carateres regulares e imprmiveis, os carateres especiais também podem ser codificados com notação <em>escape</em>:</p> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Código</th> + <th scope="col">Resultado</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>\XXX</code> (<code>XXX</code> = 1 - 3 octal digits; range of 0 - 377)</td> + <td>ISO-8859-1 character / Unicode code point between U+0000 and U+00FF</td> + </tr> + <tr> + <td><code>\'</code></td> + <td>Aspas simples</td> + </tr> + <tr> + <td><code>\"</code></td> + <td>Aspas duplas</td> + </tr> + <tr> + <td><code>\\</code></td> + <td>Barra invertida</td> + </tr> + <tr> + <td><code>\n</code></td> + <td>Nova linha</td> + </tr> + <tr> + <td><code>\r</code></td> + <td>carriage return</td> + </tr> + <tr> + <td><code>\v</code></td> + <td>Tab vertical</td> + </tr> + <tr> + <td><code>\t</code></td> + <td>Tab</td> + </tr> + <tr> + <td><code>\b</code></td> + <td>backspace</td> + </tr> + <tr> + <td><code>\f</code></td> + <td>form feed</td> + </tr> + <tr> + <td><code>\uXXXX</code> (<code>XXXX</code> = 4 hex digits; range of 0x0000 - 0xFFFF)</td> + <td>UTF-16 code unit / Unicode code point between U+0000 and U+FFFF</td> + </tr> + <tr> + <td><code>\u{X}</code> ... <code>\u{XXXXXX}</code> (<code>X…XXXXXX</code> = 1 - 6 hex digits; range of 0x0 - 0x10FFFF)</td> + <td>UTF-32 code unit / Unicode code point between U+0000 and U+10FFFF {{experimental_inline}}</td> + </tr> + <tr> + <td><code>\xXX</code> (<code>XX</code> = 2 hex digits; range of 0x00 - 0xFF)</td> + <td>ISO-8859-1 character / Unicode code point between U+0000 and U+00FF</td> + </tr> + </tbody> +</table> + +<div class="note"> +<p><strong>Note: </strong>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.</p> +</div> + +<h3 id="Strings_literais_longas"><em>Strings </em>literais longas</h3> + +<p>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.</p> + +<p>You can use the <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Addition_()">+</a> operator to append multiple strings together, like this:</p> + +<pre class="brush: js">let longString = "This is a very long string which needs " + + "to wrap across multiple lines because " + + "otherwise my code is unreadable."; +</pre> + +<p>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:</p> + +<pre class="brush: js">let longString = "This is a very long string which needs \ +to wrap across multiple lines because \ +otherwise my code is unreadable."; +</pre> + +<p>Both of these result in identical strings being created.</p> + +<h2 id="Descrição">Descrição</h2> + +<p>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 <a href="/en-US/docs/Web/JavaScript/Reference/Operators/String_Operators">+ and += string operators</a>, 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.</p> + +<h3 id="Acesso_de_caráter">Acesso de caráter</h3> + +<p>There are two ways to access an individual character in a string. The first is the {{jsxref("String.prototype.charAt()", "charAt()")}} method:</p> + +<pre class="brush: js">return 'cat'.charAt(1); // returns "a" +</pre> + +<p>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:</p> + +<pre class="brush: js">return 'cat'[1]; // returns "a" +</pre> + +<p>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.)</p> + +<h3 id="Comparação_de_strings">Comparação de <em>strings</em></h3> + +<p>C developers have the <code>strcmp()</code> function for comparing strings. In JavaScript, you just use the <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators">less-than and greater-than operators</a>:</p> + +<pre class="brush: js">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.'); +} +</pre> + +<p>A similar result can be achieved using the {{jsxref("String.prototype.localeCompare()", "localeCompare()")}} method inherited by <code>String</code> instances.</p> + +<h3 id="Distinção_entre_string_primitivas_e_objetos_String">Distinção entre <em>string</em> primitivas e objetos <em><code>String</code></em></h3> + +<p>Note that JavaScript distinguishes between <code>String</code> objects and primitive string values. (The same is true of {{jsxref("Boolean")}} and {{jsxref("Global_Objects/Number", "Numbers")}}.)</p> + +<p>String literals (denoted by double or single quotes) and strings returned from <code>String</code> calls in a non-constructor context (i.e., without using the {{jsxref("Operators/new", "new")}} keyword) are primitive strings. JavaScript automatically converts primitives to <code>String</code> objects, so that it's possible to use <code>String</code> 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.</p> + +<pre class="brush: js">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.'); +} +</pre> + +<p>A similar result can be achieved using the {{jsxref("String.prototype.localeCompare()", "localeCompare()")}} method inherited by <code>String</code> instances.</p> + +<div class="blockIndicator note"> +<p>Nota: <code>a == b</code> 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:</p> + +<p><code>function isEqual(str1, str2)<br> + {<br> + return str1.toUpperCase()===str2.toUpperCase();<br> + } // isEqual</code></p> + +<p>Upper case is used instead of lower case in this function due to problems with certain UTF-8 character conversions.</p> +</div> + +<h3 id="Distinção_entre_string_primitivas_e_objetos_String_2">Distinção entre <em>string</em> primitivas e objetos <em><code>String</code></em></h3> + +<p>Note that JavaScript distinguishes between <code>String</code> objects and primitive string values. (The same is true of {{jsxref("Boolean")}} and {{jsxref("Global_Objects/Number", "Numbers")}}.)</p> + +<p>String literals (denoted by double or single quotes) and strings returned from <code>String</code> calls in a non-constructor context (i.e., without using the {{jsxref("Operators/new", "new")}} keyword) are primitive strings. JavaScript automatically converts primitives to <code>String</code> objects, so that it's possible to use <code>String</code> 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.</p> + +<pre class="brush: js">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" +</pre> + +<p>String primitives and <code>String</code> objects also give different results when using {{jsxref("Global_Objects/eval", "eval()")}}. Primitives passed to <code>eval</code> are treated as source code; <code>String</code> objects are treated as all other objects are, by returning the object. For example:</p> + +<pre class="brush: js">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" +</pre> + +<p>For these reasons, the code may break when it encounters <code>String</code> objects when it expects a primitive string instead, although generally, authors need not worry about the distinction.</p> + +<p>A <code>String</code> object can always be converted to its primitive counterpart with the {{jsxref("String.prototype.valueOf()", "valueOf()")}} method.</p> + +<pre class="brush: js">console.log(eval(s2.valueOf())); // returns the number 4 +</pre> + +<div class="note"><strong>Nota:</strong> For another possible approach to strings in JavaScript, please read the article about <a href="/en-US/Add-ons/Code_snippets/StringView"><code>StringView</code> — a C-like representation of strings based on typed arrays</a>.</div> + +<h2 id="Propriedades">Propriedades</h2> + +<dl> + <dt>{{jsxref("String.prototype")}}</dt> + <dd>Allows the addition of properties to a <code>String</code> object.</dd> +</dl> + +<h2 id="Métodos">Métodos</h2> + +<dl> + <dt>{{jsxref("String.fromCharCode()")}}</dt> + <dd>Returns a string created by using the specified sequence of Unicode values.</dd> + <dt>{{jsxref("String.fromCodePoint()")}}</dt> + <dd>Returns a string created by using the specified sequence of code points.</dd> + <dt>{{jsxref("String.raw()")}} {{experimental_inline}}</dt> + <dd>Returns a string created from a raw template string.</dd> +</dl> + +<h2 id="Instâncias_de_String">Instâncias de <em><code>String</code></em></h2> + +<h3 id="Propriedades_2">Propriedades</h3> + +<div>{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/prototype', 'Properties')}}</div> + +<h3 id="Métodos_2">Métodos</h3> + +<h4 id="Methods_unrelated_to_HTML">Methods unrelated to HTML</h4> + +<div>{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/prototype', 'Methods_unrelated_to_HTML')}}</div> + +<h4 id="HTML_wrapper_methods">HTML wrapper methods</h4> + +<div>{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/prototype', 'HTML_wrapper_methods')}}</div> + +<h2 id="Exemplos">Exemplos</h2> + +<h3 id="Conversão_de_String">Conversão de <em>String</em></h3> + +<p>It's possible to use <code>String</code> 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:</p> + +<pre class="brush: js">var outputStrings = []; +for (var i = 0, n = inputValues.length; i < n; ++i) { + outputStrings.push(String(inputValues[i])); +} +</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('ESDraft', '#sec-string-objects', 'String')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-string-objects', 'String')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.5', 'String')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_de_navegador">Compatibilidade de navegador</h2> + + + +<p>{{Compat("javascript.builtins.String",2)}}</p> + +<h2 id="Consulte_também">Consulte também:</h2> + +<ul> + <li>{{domxref("DOMString")}}</li> + <li><a href="/en-US/Add-ons/Code_snippets/StringView"><code>StringView</code> — a C-like representation of strings based on typed arrays</a></li> + <li><a href="/en-US/docs/Web/API/DOMString/Binary">Binary strings</a></li> +</ul> 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 new file mode 100644 index 0000000000..721fb3c913 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/global_objects/string/indexof/index.html @@ -0,0 +1,191 @@ +--- +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 +--- +<div>{{JSRef}}</div> + +<p>O método <strong><code>indexOf()</code></strong> retorna o indíce da primeira ocorrência do valor especificado no objeto {{jsxref("String")}}, começando a procura a partir de <code>fromIndex</code>. Retorna -1 se o valor não for encontrado.</p> + +<h2 id="Sintaxe">Sintaxe</h2> + +<pre class="syntaxbox"><code><var>str</var>.indexOf(<var>searchValue</var>[, <var>fromIndex</var>]</code>)</pre> + +<h3 id="Parâmetros">Parâmetros</h3> + +<dl> + <dt><code>searchValue</code></dt> + <dd>Uma string com o valor pelo qual se procura.</dd> + <dt><code>fromIndex</code> {{optional_inline}}</dt> + <dd>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 <code>fromIndex < 0</code> a procura é feita em toda a string (o mesmo que passar o valor 0). Se <code>fromIndex >= str.length</code>, o método retornará -1, exceção feita quando o valor de <code>searchValue</code> é uma string vazia, nesse caso retorna <code>str.length</code>.</dd> +</dl> + +<h2 id="Descrição">Descrição</h2> + +<p>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 <code>stringName,</code> é <code>stringName.length - 1</code>.</p> + +<pre class="brush: js">'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 +</pre> + +<h3 id="Case-sensitivity">Case-sensitivity</h3> + +<p>O método <code>indexOf()</code> é sensível a maiúsculas e minúsculas. Por exemplo, a seguinte expressão retorna -1:</p> + +<pre class="brush: js">'Blue Whale'.indexOf('blue'); // retorna -1 +</pre> + +<h3 id="Verificando_ocorrências">Verificando ocorrências</h3> + +<p>Repara que '0' não é avaliado como <code>true</code> e '-1' não é avaliado como <code>false</code>. Sendo assim, a forma correta de verificar se uma string específica existe dentro de outra string deverá ser:</p> + +<pre class="brush: js">'Blue Whale'.indexOf('Blue') !== -1; // true +'Blue Whale'.indexOf('Bloe') !== -1; // false +</pre> + +<h2 id="Exemplos">Exemplos</h2> + +<h3 id="Usando_indexOf()_e_lastIndexOf()">Usando <code>indexOf()</code> e <code>lastIndexOf()</code></h3> + +<p>O seguinte exemplo usa <code>indexOf()</code> e {{jsxref("String.prototype.lastIndexOf()", "lastIndexOf()")}} para localizar valores na string <code>"Brave new world"</code>.</p> + +<pre class="brush: js">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 +</pre> + +<h3 id="indexOf()_e_sensibilidade_a_maiúsculas_e_minúsculas"><code>indexOf()</code> e sensibilidade a maiúsculas e minúsculas</h3> + +<p>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 <code>indexOf()</code> é sensível a maiúsculas e minúsculas, a string <code>"cheddar"</code> não é encontrada em <code>myCapString</code>, logo o segundo método <code>console.log()</code> apresenta -1.</p> + +<pre class="brush: js">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 +</pre> + +<h3 id="Usando_indexOf()_para_contar_as_ocorrências_de_uma_letra_numa_string">Usando <code>indexOf()</code> para contar as ocorrências de uma letra numa string</h3> + +<p>O seguinte exemplo atribuí à variável <code>count</code> o número de ocorrências da letra 'e' na string <code>str</code>:</p> + +<pre class="brush: js">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 +</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Definição inicial.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.5.4.7', 'String.prototype.indexOf')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-string.prototype.indexof', 'String.prototype.indexOf')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_dos_browsers">Compatibilidade dos browsers</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Funcionalidade</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Suporte básico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Funcionalidade</th> + <th>Android</th> + <th>Chrome para Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Suporte básico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li>{{jsxref("String.prototype.charAt()")}}</li> + <li>{{jsxref("String.prototype.lastIndexOf()")}}</li> + <li>{{jsxref("String.prototype.split()")}}</li> + <li>{{jsxref("Array.prototype.indexOf()")}}</li> +</ul> 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 new file mode 100644 index 0000000000..7774170252 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/global_objects/string/length/index.html @@ -0,0 +1,125 @@ +--- +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 +--- +<div>{{JSRef}}</div> + +<p>A propriedade <strong><code>length</code></strong> representa o comprimento de uma string.</p> + +<h2 id="Sintaxe">Sintaxe</h2> + +<pre class="syntaxbox"><code><var>str</var>.length</code></pre> + +<h2 id="Descrição">Descrição</h2> + +<p>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 <code>length</code> não seja igual ao número de caracteres numa string.</p> + +<p>Para uma string vazia, <code>length</code> is 0.</p> + +<p>A propriedade estática (static) <code>String.length</code> retorna o valor 1.</p> + +<h2 id="Exemplos">Exemplos</h2> + +<h3 id="Uso_simples">Uso simples</h3> + +<pre class="brush: js">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" */ +</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Definição inicial. Implementado em JavaScript 1.0.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.5.5.1', 'String.prototype.length')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-properties-of-string-instances-length', 'String.prototype.length')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_dos_browsers">Compatibilidade dos browsers</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Funcionalidade</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Suporte básico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Funcionalidade</th> + <th>Android</th> + <th>Chrome para Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Suporte básico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li><a href="http://developer.teradata.com/blog/jasonstrimpel/2011/11/javascript-string-length-and-internationalizing-web-applications">JavaScript <code>String.length</code> and Internationalizing Web Applications</a></li> +</ul> 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 new file mode 100644 index 0000000000..8ef29112f8 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/global_objects/string/trim/index.html @@ -0,0 +1,139 @@ +--- +title: String.prototype.trim() +slug: Web/JavaScript/Reference/Global_Objects/String/Trim +tags: + - ECMAScript 5 + - JavaScript + - Prototipo + - Referencia + - String + - metodo +translation_of: Web/JavaScript/Reference/Global_Objects/String/Trim +--- +<div>{{JSRef}}</div> + +<p>O método <strong><code>trim()</code></strong> elimina espaço em branco de ambos os extremos dum <em>string</em>. 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.).</p> + +<h2 id="Sintaxe">Sintaxe</h2> + +<pre class="syntaxbox"><code><var>str</var>.trim()</code></pre> + +<h3 id="Valor_devolvido">Valor devolvido</h3> + +<p>Um novo <em>string</em> que representa o <em>string</em> que chamou despojado do espaço em branco de ambos os extremos.</p> + +<h2 id="Descrição">Descrição</h2> + +<p>O método <code>trim()</code> devolve o <em>string</em> despojado do espaço em branco de ambos os extremos. <code>trim()</code> não afecta o valor do <em>string</em> em si.</p> + +<h2 id="Exemplos">Exemplos</h2> + +<h3 id="Using_trim()">Using <code>trim()</code></h3> + +<p>O exemplo que se segue mostra o <em>string</em> <code>'foo' em minúsculas</code>:</p> + +<pre class="brush: js">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' +</pre> + +<h2 id="Polyfill">Polyfill</h2> + +<p>Ao correr o código que se segue antes de qualquer outro criará <code>trim()</code> se não estiver nativamente disponível.</p> + +<pre class="brush: js">if (!String.prototype.trim) { + String.prototype.trim = function () { + return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, ''); + }; +} +</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.5.4.20', 'String.prototype.trim')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>Definição inicial. Implementada em JavaScript 1.8.1.</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-string.prototype.trim', 'String.prototype.trim')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.prototype.trim', 'String.prototype.trim')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_de_navegadores">Compatibilidade de navegadores</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Suporte básico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("1.9.1")}}</td> + <td>{{CompatIE("9")}}</td> + <td>{{CompatOpera("10.5")}}</td> + <td>{{CompatSafari("5")}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Suporte básico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li>{{jsxref("String.prototype.trimLeft()")}} {{non-standard_inline}}</li> + <li>{{jsxref("String.prototype.trimRight()")}} {{non-standard_inline}}</li> +</ul> 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 new file mode 100644 index 0000000000..3ba9666678 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/global_objects/symbol/hasinstance/index.html @@ -0,0 +1,114 @@ +--- +title: Symbol.hasInstance +slug: Web/JavaScript/Reference/Global_Objects/Symbol/hasInstance +tags: + - Propriedade + - Referencia +translation_of: Web/JavaScript/Reference/Global_Objects/Symbol/hasInstance +--- +<div>{{JSRef}}</div> + +<p>O symbol bem-conhecido <strong><code>Symbol.hasInstance</code></strong> é 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.</p> + +<div>{{js_property_attributes(0,0,0)}}</div> + +<h2 id="Exemplos">Exemplos</h2> + +<p>Tu podes implementar o comportamento customizado do seu <code>instanceof</code> deste jeito; por exemplo:</p> + +<pre class="brush: js">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</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-symbol.hasinstance', 'Symbol.hasInstance')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-symbol.hasinstance', 'Symbol.hasInstance')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_com_os_navegadores">Compatibilidade com os navegadores</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatChrome(51)}}</td> + <td>{{ CompatGeckoDesktop(50) }}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{ CompatGeckoMobile(50) }}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Veja_também">Veja também</h2> + +<ul> + <li>{{jsxref("Operators/instanceof", "instanceof")}}</li> + <li>{{jsxref("Global_Objects/Object/isPrototypeOf", "isPrototypeOf()")}}</li> +</ul> 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 new file mode 100644 index 0000000000..00148cd9b1 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/global_objects/symbol/index.html @@ -0,0 +1,458 @@ +--- +title: Symbol +slug: Web/JavaScript/Reference/Global_Objects/Symbol +tags: + - ECMAScript6 + - JavaScript + - NeedsTranslation + - Symbol + - TopicStub +translation_of: Web/JavaScript/Reference/Global_Objects/Symbol +--- +<div>{{JSRef}}</div> + +<p>A <strong>symbol</strong> is a unique and immutable data type. It may be used as an identifier for object properties. The <em>Symbol object</em> is an implicit object wrapper for the symbol {{Glossary("Primitive", "primitive data type")}}.</p> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox">Symbol(<em>[description]</em>)</pre> + +<h3 id="Parameters">Parameters</h3> + +<dl> + <dt><code>description</code> {{optional_inline}}</dt> + <dd>Optional, string. A description of the symbol which can be used for debugging but not to access the symbol itself.</dd> +</dl> + +<h2 id="Description">Description</h2> + +<p>To create a new primitive symbol, you write <code>Symbol()</code> with an optional string as its description:</p> + +<pre class="brush: js">var sym1 = Symbol(); +var sym2 = Symbol("foo"); +var sym3 = Symbol("foo"); +</pre> + +<p>The above code creates three new symbols. Note that <code>Symbol("foo")</code> does not coerce the string "foo" into a symbol. It creates a new symbol each time:</p> + +<pre class="brush: js">Symbol("foo") === Symbol("foo"); // false</pre> + +<p>The following syntax with the {{jsxref("Operators/new", "new")}} operator will throw a {{jsxref("TypeError")}}:</p> + +<pre class="brush: js">var sym = new Symbol(); // TypeError</pre> + +<p>This prevents authors from creating an explicit <code>Symbol</code> 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, <code>new Boolean</code>, <code>new String</code> and <code>new Number</code>).</p> + +<p>If you really want to create a <code>Symbol</code> wrapper object, you can use the <code>Object()</code> function:</p> + +<pre class="brush: js">var sym = Symbol("foo"); +typeof sym; // "symbol" +var symObj = Object(sym); +typeof symObj; // "object" +</pre> + +<h3 id="Shared_symbols_in_the_global_symbol_registry">Shared symbols in the global symbol registry</h3> + +<p>The above syntax using the <code>Symbol()</code> 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.</p> + +<h3 id="Finding_symbol_properties_on_objects">Finding symbol properties on objects</h3> + +<p>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.</p> + +<h2 id="Properties">Properties</h2> + +<dl> + <dt><code>Symbol.length</code></dt> + <dd>Length property whose value is 0.</dd> + <dt>{{jsxref("Symbol.prototype")}}</dt> + <dd>Represents the prototype for the <code>Symbol</code> constructor.</dd> +</dl> + +<h3 id="Well-known_symbols">Well-known symbols</h3> + +<p>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:</p> + +<h4 id="Iteration_symbols">Iteration symbols</h4> + +<dl> + <dt>{{jsxref("Symbol.iterator")}}</dt> + <dd>A method returning the default iterator for an object. Used by <a href="/en-US/docs/Web/JavaScript/Reference/Statements/for...of"><code>for...of</code></a>.</dd> +</dl> + +<h4 id="Regular_expression_symbols">Regular expression symbols</h4> + +<dl> + <dt>{{jsxref("Symbol.match")}}</dt> + <dd>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()")}}.</dd> + <dt>{{jsxref("Symbol.replace")}}</dt> + <dd>A method that replaces matched substrings of a string. Used by {{jsxref("String.prototype.replace()")}}.</dd> + <dt>{{jsxref("Symbol.search")}}</dt> + <dd>A method that returns the index within a string that matches the regular expression. Used by {{jsxref("String.prototype.search()")}}.</dd> + <dt>{{jsxref("Symbol.split")}}</dt> + <dd>A method that splits a string at the indices that match a regular expression. Used by {{jsxref("String.prototype.split()")}}.</dd> +</dl> + +<h4 id="Other_symbols">Other symbols</h4> + +<dl> + <dt>{{jsxref("Symbol.hasInstance")}}</dt> + <dd>A method determining if a constructor object recognizes an object as its instance. Used by {{jsxref("Operators/instanceof", "instanceof")}}.</dd> + <dt>{{jsxref("Symbol.isConcatSpreadable")}}</dt> + <dd>A Boolean value indicating if an object should be flattened to its array elements. Used by {{jsxref("Array.prototype.concat()")}}.</dd> + <dt>{{jsxref("Symbol.unscopables")}}</dt> + <dd>An object value of whose own and inherited property names are excluded from the <code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/with">with</a></code> environment bindings of the associated object.</dd> + <dt>{{jsxref("Symbol.species")}}</dt> + <dd>A constructor function that is used to create derived objects.</dd> + <dt>{{jsxref("Symbol.toPrimitive")}}</dt> + <dd>A method converting an object to a primitive value.</dd> + <dt>{{jsxref("Symbol.toStringTag")}}</dt> + <dd>A string value used for the default description of an object. Used by {{jsxref("Object.prototype.toString()")}}.</dd> +</dl> + +<h2 id="Methods">Methods</h2> + +<dl> + <dt>{{jsxref("Symbol.for()", "Symbol.for(key)")}}</dt> + <dd>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.</dd> + <dt>{{jsxref("Symbol.keyFor", "Symbol.keyFor(sym)")}}</dt> + <dd>Retrieves a shared symbol key from the global symbol registry for the given symbol.</dd> +</dl> + +<h2 id="Symbol_prototype"><code>Symbol</code> prototype</h2> + +<p>All Symbols inherit from {{jsxref("Symbol.prototype")}}.</p> + +<h3 id="Properties_2">Properties</h3> + +<p>{{page('en-US/Web/JavaScript/Reference/Global_Objects/Symbol/prototype','Properties')}}</p> + +<h3 id="Methods_2">Methods</h3> + +<p>{{page('en-US/Web/JavaScript/Reference/Global_Objects/Symbol/prototype','Methods')}}</p> + +<h2 id="Examples">Examples</h2> + +<h3 id="Using_the_typeof_operator_with_symbols">Using the <code>typeof</code> operator with symbols</h3> + +<p>The {{jsxref("Operators/typeof", "typeof")}} operator can help you to identify symbols.</p> + +<pre class="brush: js">typeof Symbol() === 'symbol' +typeof Symbol('foo') === 'symbol' +typeof Symbol.iterator === 'symbol' +</pre> + +<h3 id="Symbol_type_conversions">Symbol type conversions</h3> + +<p>Some things to note when working with type conversion of symbols.</p> + +<ul> + <li>When trying to convert a symbol to a number, a {{jsxref("TypeError")}} will be thrown<br> + (e.g. <code>+sym</code> or <code>sym | 0</code>).</li> + <li>When using loose equality, <code>Object(sym) == sym</code> returns <code>true.</code></li> + <li><code>Symbol("foo") + "bar" </code>throws a {{jsxref("TypeError")}} (can't convert symbol to string). This prevents you from silently creating a new string property name from a symbol, for example.</li> + <li>The <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#String_conversion">"safer" <code>String(sym)</code> conversion</a> works like a call to {{jsxref("Symbol.prototype.toString()")}} with symbols, but note that <code>new String(sym)</code> will throw.</li> +</ul> + +<h3 id="Symbols_and_for...in_iteration">Symbols and <code>for...in</code> iteration</h3> + +<p>Symbols are not enumerable in <a href="/en-US/docs/Web/JavaScript/Reference/Statements/for...in"><code>for...in</code></a> iterations. In addition, {{jsxref("Object.getOwnPropertyNames()")}} will not return symbol object properties, however, you can use {{jsxref("Object.getOwnPropertySymbols()")}} to get these.</p> + +<pre class="brush: js">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" +}</pre> + +<h3 id="Symbols_and_JSON.stringify()">Symbols and <code>JSON.stringify()</code></h3> + +<p>Symbol-keyed properties will be completely ignored when using <code>JSON.stringify()</code>:</p> + +<pre class="brush: js">JSON.stringify({[Symbol("foo")]: "foo"}); +// '{}'</pre> + +<p>For more details, see {{jsxref("JSON.stringify()")}}.</p> + +<h3 id="Symbol_wrapper_objects_as_property_keys">Symbol wrapper objects as property keys</h3> + +<p>When a Symbol wrapper object is used as a property key, this object will be coerced to its wrapped symbol:</p> + +<pre class="brush: js">var sym = Symbol("foo"); +var obj = {[sym]: 1}; +obj[sym]; // 1 +obj[Object(sym)]; // still 1 +</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-symbol-objects', 'Symbol')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>Initial definition</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-symbol-objects', 'Symbol')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatChrome(38)}}</td> + <td>{{CompatGeckoDesktop(36)}}</td> + <td>{{CompatNo}}</td> + <td>25</td> + <td>9</td> + </tr> + <tr> + <td>Symbol.iterator (@@iterator)</td> + <td>{{CompatChrome(38)}}</td> + <td>{{CompatGeckoDesktop(36)}}</td> + <td>{{CompatNo}}</td> + <td>25</td> + <td>9</td> + </tr> + <tr> + <td>Symbol.unscopables (@@unscopables)</td> + <td>{{CompatChrome(38)}}</td> + <td>{{CompatGeckoDesktop(48)}}</td> + <td>{{CompatNo}}</td> + <td>25</td> + <td>9</td> + </tr> + <tr> + <td>Symbol.match (@@match)</td> + <td>{{CompatChrome(50)}}</td> + <td>{{CompatGeckoDesktop(40)}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>Symbol.species (@@species)</td> + <td>{{CompatChrome(51)}}</td> + <td>{{CompatGeckoDesktop(41)}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>Symbol.toPrimitive (@@toPrimitive)</td> + <td>{{CompatChrome(48)}}</td> + <td>{{CompatGeckoDesktop(44)}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>Symbol.replace (@@replace)</td> + <td>{{CompatChrome(50)}}</td> + <td>{{CompatGeckoDesktop(48)}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>Symbol.search (@@search)</td> + <td>{{CompatChrome(50)}}</td> + <td>{{CompatGeckoDesktop(48)}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>Symbol.split (@@split)</td> + <td>{{CompatChrome(50)}}</td> + <td>{{CompatGeckoDesktop(48)}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>Symbol.isConcatSpreadable (@@isconcatspreadable)</td> + <td>{{CompatChrome(48)}}</td> + <td>{{CompatGeckoDesktop(48)}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>Symbol.hasInstance (@@hasInstance)</td> + <td>{{CompatChrome(51)}}</td> + <td>{{CompatGeckoDesktop(50)}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>Symbol.toStringTag (@@toStringTag)</td> + <td>{{CompatChrome(49)}}</td> + <td>{{CompatGeckoDesktop(51)}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatChrome(38)}}</td> + <td>{{CompatGeckoMobile(36)}}</td> + <td>{{CompatNo}}</td> + <td>25</td> + <td>9</td> + </tr> + <tr> + <td>Symbol.iterator (@@iterator)</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatChrome(38)}}</td> + <td>{{CompatGeckoMobile(36)}}</td> + <td>{{CompatNo}}</td> + <td>25</td> + <td>9</td> + </tr> + <tr> + <td>Symbol.unscopables (@@unscopables)</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatChrome(38)}}</td> + <td>{{CompatGeckoMobile(48)}}</td> + <td>{{CompatNo}}</td> + <td>25</td> + <td>9</td> + </tr> + <tr> + <td>Symbol.match (@@match)</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile(40)}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>Symbol.species (@@species)</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile(41)}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>Symbol.toPrimitive (@@toPrimitive)</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile(44)}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>Symbol.replace (@@replace)</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile(48)}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>Symbol.search (@@search)</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile(48)}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>Symbol.split (@@split)</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile(48)}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>Symbol.isConcatSpreadable (@@isconcatspreadable)</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile(48)}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>Symbol.hasInstance (@@hasInstance)</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile(50)}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>Symbol.toStringTag (@@toStringTag)</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile(51)}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Glossary/Symbol">Glossary: Symbol data type</a></li> + <li>{{jsxref("Operators/typeof", "typeof")}}</li> + <li><a href="/en-US/docs/Web/JavaScript/Data_structures">Data types and data structures</a></li> + <li><a href="https://hacks.mozilla.org/2015/06/es6-in-depth-symbols/">"ES6 In Depth: Symbols" on hacks.mozilla.org</a></li> +</ul> diff --git a/files/pt-pt/web/javascript/reference/index.html b/files/pt-pt/web/javascript/reference/index.html new file mode 100644 index 0000000000..aa2f94e880 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/index.html @@ -0,0 +1,307 @@ +--- +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 +--- +<div>{{JsSidebar}}</div> + +<p>Esta parte da secção de JavaScript na MDN serve como um repositório de factos sobre a linguage JavaScript. Leia mais <a href="/pt-PT/docs/Web/JavaScript/Reference/Sobre">sobre esta referência</a>.</p> + +<h2 id="Integrações">Integrações</h2> + +<p><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects">Objetos integrados padrões de JavaScript</a>, em conjunto com os seus métodos e propriedades.</p> + +<ul class="card-grid"> + <li><span>Propriedades de Valor</span> + + <p>{{JSxRef("Infinity")}}<br> + {{JSxRef("NaN")}}<br> + {{JSxRef("undefined")}}<br> + {{JSxRef("globalThis")}}</p> + </li> + <li><span>Propriedades de Função</span> + <p>{{JSxRef("Global_Objects/eval", "eval()")}}<br> + {{JSxRef("Global_Objects/isFinite", "isFinite()")}}<br> + {{JSxRef("Global_Objects/isNaN", "isNaN()")}}<br> + {{JSxRef("Global_Objects/parseFloat", "parseFloat()")}}<br> + {{JSxRef("Global_Objects/parseInt", "parseInt()")}}<br> + {{JSxRef("Global_Objects/decodeURI", "decodeURI()")}}<br> + {{JSxRef("Global_Objects/decodeURIComponent", "decodeURIComponent()")}}<br> + {{JSxRef("Global_Objects/encodeURI", "encodeURI()")}}<br> + {{JSxRef("Global_Objects/encodeURIComponent", "encodeURIComponent()")}}</p> + </li> + <li><span>Objetos Fundamentais</span> + <p>{{JSxRef("Object")}}<br> + {{JSxRef("Function")}}<br> + {{JSxRef("Boolean")}}<br> + {{JSxRef("Symbol")}}</p> + </li> + <li><span>Objetos de Erro</span> + <p>{{JSxRef("Error")}}<br> + {{JSxRef("AggregateError")}}<br> + {{JSxRef("EvalError")}}<br> + {{JSxRef("InternalError")}}<br> + {{JSxRef("RangeError")}}<br> + {{JSxRef("ReferenceError")}}<br> + {{JSxRef("SyntaxError")}}<br> + {{JSxRef("TypeError")}}<br> + {{JSxRef("URIError")}}</p> + </li> +</ul> + +<ul class="card-grid"> + <li><span>Números e Datas</span> + + <p>{{JSxRef("Number")}}<br> + {{JSxRef("BigInt")}}<br> + {{JSxRef("Math")}}<br> + {{JSxRef("Date")}}</p> + </li> + <li><span>Processamento de Texto</span> + <p>{{JSxRef("String")}}<br> + {{JSxRef("RegExp")}}</p> + </li> + <li><span>Coleções Indexadas</span><a href="/en-US/docs/Web/JavaScript/Guide/Numbers_and_dates#Numbers"> </a>{{JSxRef("Array")}}<br> + {{JSxRef("Int8Array")}}<br> + {{JSxRef("Uint8Array")}}<br> + {{JSxRef("Uint8ClampedArray")}}<br> + {{JSxRef("Int16Array")}}<br> + {{JSxRef("Uint16Array")}}<br> + {{JSxRef("Int32Array")}}<br> + {{JSxRef("Uint32Array")}}<br> + {{JSxRef("Float32Array")}}<br> + {{JSxRef("Float64Array")}}<br> + {{JSxRef("BigInt64Array")}}<br> + {{JSxRef("BigUint64Array")}}</li> + <li><span>Coleções ''Keyed''</span> + <p>{{JSxRef("Map")}}<br> + {{JSxRef("Set")}}<br> + {{JSxRef("WeakMap")}}<br> + {{JSxRef("WeakSet")}}</p> + </li> +</ul> + +<ul class="card-grid"> + <li><span>Dados Estruturados</span> + + <p>{{JSxRef("ArrayBuffer")}}<br> + {{JSxRef("SharedArrayBuffer")}}<br> + {{JSxRef("Atomics")}}<br> + {{JSxRef("DataView")}}<br> + {{JSxRef("JSON")}}</p> + </li> + <li><span>Abstração de Controlo</span> + <p>{{JSxRef("Promise")}}<br> + {{JSxRef("Generator")}}<br> + {{JSxRef("GeneratorFunction")}}<br> + {{JSxRef("AsyncFunction")}}</p> + </li> + <li><span>Reflexão</span> + <p>{{JSxRef("Reflect")}}<br> + {{JSxRef("Proxy")}}</p> + </li> + <li><span>Internacionalização</span> + <p>{{JSxRef("Intl")}}<br> + {{JSxRef("Global_Objects/Collator", "Intl.Collator")}}<br> + {{JSxRef("Global_Objects/DateTimeFormat", "Intl.DateTimeFormat")}}<br> + {{JSxRef("Global_Objects/ListFormat", "Intl.ListFormat")}}<br> + {{JSxRef("Global_Objects/NumberFormat", "Intl.NumberFormat")}}<br> + {{JSxRef("Global_Objects/PluralRules", "Intl.PluralRules")}}<br> + {{JSxRef("Global_Objects/RelativeTimeFormat", "Intl.RelativeTimeFormat")}}<br> + {{JSxRef("Global_Objects/Locale", "Intl.Locale")}}</p> + </li> +</ul> + +<ul class="card-grid"> + <li><span>WebAssembly</span> + + <p>{{JSxRef("WebAssembly")}}<br> + {{JSxRef("WebAssembly.Module")}}<br> + {{JSxRef("WebAssembly.Instance")}}<br> + {{JSxRef("WebAssembly.Memory")}}<br> + {{JSxRef("WebAssembly.Table")}}<br> + {{JSxRef("WebAssembly.CompileError")}}<br> + {{JSxRef("WebAssembly.LinkError")}}<br> + {{JSxRef("WebAssembly.RuntimeError")}}</p> + </li> +</ul> + +<h2 id="Declações_Statements">Declações (Statements)</h2> + +<p><a href="/pt-PT/docs/Web/JavaScript/Reference/Extratos_e_declarações">Declarações e instruções de JavaScript</a></p> + +<ul class="card-grid"> + <li><span>Control flow</span>{{jsxref("Statements/block", "Block")}}<br> + {{jsxref("Statements/break", "break")}}<br> + {{jsxref("Statements/continue", "continue")}}<br> + {{jsxref("Statements/Empty", "Empty")}}<br> + {{jsxref("Statements/if...else", "if...else")}}<br> + {{jsxref("Statements/switch", "switch")}}<br> + {{jsxref("Statements/throw", "throw")}}<br> + {{jsxref("Statements/try...catch", "try...catch")}}</li> + <li><span>Declarations</span> + <p>{{jsxref("Statements/var", "var")}}<br> + {{jsxref("Statements/let", "let")}}<br> + {{jsxref("Statements/const", "const")}}</p> + </li> + <li><span>Functions and classes</span> + <p>{{jsxref("Statements/function", "function")}}<br> + {{jsxref("Statements/function*", "function*")}}<br> + {{jsxref("Statements/async_function", "async function")}}<br> + {{jsxref("Statements/return", "return")}}<br> + {{jsxref("Statements/class", "class")}}</p> + </li> + <li><span>Iterations</span> + <p>{{jsxref("Statements/do...while", "do...while")}}<br> + {{jsxref("Statements/for", "for")}}<br> + {{jsxref("Statements/for_each...in", "for each...in")}}<br> + {{jsxref("Statements/for...in", "for...in")}}<br> + {{jsxref("Statements/for...of", "for...of")}}<br> + {{jsxref("Statements/for-await...of", "for await...of")}}<br> + {{jsxref("Statements/while", "while")}}</p> + </li> +</ul> + +<ul class="card-grid"> + <li><span>Outros</span> + + <p>{{jsxref("Statements/debugger", "debugger")}}<br> + {{jsxref("Statements/import", "import")}}<br> + {{jsxref("Statements/label", "label")}}<br> + {{jsxref("Statements/with", "with")}}</p> + </li> +</ul> + +<h2 id="Expressões_e_operadores">Expressões e operadores</h2> + +<p><a href="/pt-PT/docs/Web/JavaScript/Reference/Operadores">Expressões e operadores de JavaScript</a>. </p> + +<div> +<ul class="card-grid"> + <li><span>Primary expressions</span>{{JSxRef("Operators/this", "this")}}<br> + {{JSxRef("Operators/function", "function")}}<br> + {{JSxRef("Operators/class", "class")}}<br> + {{JSxRef("Operators/function*", "function*")}}<br> + {{JSxRef("Operators/yield", "yield")}}<br> + {{JSxRef("Operators/yield*", "yield*")}}<br> + {{JSxRef("Operators/async_function", "async function")}}<br> + {{JSxRef("Operators/await", "await")}}<br> + {{JSxRef("Global_Objects/Array", "[]")}}<br> + {{JSxRef("Operators/Object_initializer", "{}")}}<br> + {{JSxRef("Global_Objects/RegExp", "/ab+c/i")}}<br> + {{JSxRef("Operators/Grouping", "( )")}}<br> + {{JSxRef("null")}}</li> + <li><span>Left-hand-side expressions</span> + <p>{{JSxRef("Operators/Property_accessors", "Property accessors", "", 1)}}<br> + {{JSxRef("Operators/new", "new")}}<br> + {{JSxRef("Operators/new%2Etarget", "new.target")}}<br> + {{JSxRef("Operators/super", "super")}}<br> + {{JSxRef("Operators/Spread_syntax", "...obj")}}</p> + </li> + <li><span>Increment & decrement</span> + <p>{{JSxRef("Operators/Arithmetic_Operators", "A++", "#Increment")}}<br> + {{JSxRef("Operators/Arithmetic_Operators", "A--", "#Decrement")}}<br> + {{JSxRef("Operators/Arithmetic_Operators", "++A", "#Increment")}}<br> + {{JSxRef("Operators/Arithmetic_Operators", "--A", "#Decrement")}}</p> + </li> + <li><span>Unary operators</span> + <p>{{JSxRef("Operators/delete", "delete")}}<br> + {{JSxRef("Operators/void", "void")}}<br> + {{JSxRef("Operators/typeof", "typeof")}}<br> + {{JSxRef("Operators/Arithmetic_Operators", "+", "#Unary_plus")}}<br> + {{JSxRef("Operators/Arithmetic_Operators", "-", "#Unary_negation")}}<br> + {{JSxRef("Operators/Bitwise_Operators", "~", "#Bitwise_NOT")}}<br> + {{JSxRef("Operators/Logical_Operators", "!", "#Logical_NOT")}}</p> + </li> +</ul> + +<ul class="card-grid"> + <li><span>Arithmetic operators</span> + + <p>{{JSxRef("Operators/Arithmetic_Operators", "+", "#Addition")}}<br> + {{JSxRef("Operators/Arithmetic_Operators", "-", "#Subtraction")}}<br> + {{JSxRef("Operators/Arithmetic_Operators", "/", "#Division")}}<br> + {{JSxRef("Operators/Arithmetic_Operators", "*", "#Multiplication")}}<br> + {{JSxRef("Operators/Arithmetic_Operators", "%", "#Remainder")}}<br> + {{JSxRef("Operators/Arithmetic_Operators", "**", "#Exponentiation")}}</p> + </li> + <li><span>Relational operators</span> + <p>{{JSxRef("Operators/in", "in")}}<br> + {{JSxRef("Operators/instanceof", "instanceof")}}<br> + {{JSxRef("Operators/Comparison_Operators", "<", "#Less_than_operator")}}<br> + {{JSxRef("Operators/Comparison_Operators", ">", "#Greater_than_operator")}}<br> + {{JSxRef("Operators/Comparison_Operators", "<=", "#Less_than_or_equal_operator")}}<br> + {{JSxRef("Operators/Comparison_Operators", ">=", "#Greater_than_or_equal_operator")}}</p> + </li> + <li><span>Equality operators</span> + <p>{{JSxRef("Operators/Comparison_Operators", "==", "#Equality")}}<br> + {{JSxRef("Operators/Comparison_Operators", "!=", "#Inequality")}}<br> + {{JSxRef("Operators/Comparison_Operators", "===", "#Identity")}}<br> + {{JSxRef("Operators/Comparison_Operators", "!==", "#Nonidentity")}}</p> + </li> + <li><span>Bitwise shift operators</span> + <p>{{JSxRef("Operators/Bitwise_Operators", "<<", "#Left_shift")}}<br> + {{JSxRef("Operators/Bitwise_Operators", ">>", "#Right_shift")}}<br> + {{JSxRef("Operators/Bitwise_Operators", ">>>", "#Unsigned_right_shift")}}</p> + </li> +</ul> + +<ul class="card-grid"> + <li><span>Binary bitwise operators</span>{{JSxRef("Operators/Bitwise_Operators", "&", "#Bitwise_AND")}}<br> + {{JSxRef("Operators/Bitwise_Operators", "|", "#Bitwise_OR")}}<br> + {{JSxRef("Operators/Bitwise_Operators", "^", "#Bitwise_XOR")}}</li> + <li><span>Binary logical operators</span> + <p>{{JSxRef("Operators/Logical_Operators", "&&", "#Logical_AND")}}<br> + {{JSxRef("Operators/Logical_Operators", "||", "#Logical_OR")}}</p> + </li> + <li><span>Ternary operator</span> + <p>{{JSxRef("Operators/Conditional_Operator", "(condition ? ifTrue : ifFalse)")}}</p> + </li> + <li><span>Assignment operators</span> + <p>{{JSxRef("Operators/Assignment_Operators", "=", "#Assignment")}}<br> + {{JSxRef("Operators/Assignment_Operators", "*=", "#Multiplication_assignment")}}<br> + {{JSxRef("Operators/Assignment_Operators", "/=", "#Division_assignment")}}<br> + {{JSxRef("Operators/Assignment_Operators", "%=", "#Remainder_assignment")}}<br> + {{JSxRef("Operators/Assignment_Operators", "+=", "#Addition_assignment")}}<br> + {{JSxRef("Operators/Assignment_Operators", "-=", "#Subtraction_assignment")}}<br> + {{JSxRef("Operators/Assignment_Operators", "<<=", "#Left_shift_assignment")}}<br> + {{JSxRef("Operators/Assignment_Operators", ">>=", "#Right_shift_assignment")}}<br> + {{JSxRef("Operators/Assignment_Operators", ">>>=", "#Unsigned_right_shift_assignment")}}<br> + {{JSxRef("Operators/Assignment_Operators", "&=", "#Bitwise_AND_assignment")}}<br> + {{JSxRef("Operators/Assignment_Operators", "^=", "#Bitwise_XOR_assignment")}}<br> + {{JSxRef("Operators/Assignment_Operators", "|=", "#Bitwise_OR_assignment")}}<br> + {{JSxRef("Operators/Destructuring_assignment", "[a, b] = [1, 2]")}}<br> + {{JSxRef("Operators/Destructuring_assignment", "{a, b} = {a:1, b:2}")}}</p> + </li> +</ul> +</div> + +<h2 id="Funções">Funções</h2> + +<p>This chapter documents how to work with <a href="/en-US/docs/Web/JavaScript/Reference/Functions">JavaScript functions</a> to develop your applications.</p> + +<ul> + <li><a href="/pt-PT/docs/Web/JavaScript/Reference/Funcoes/arguments"><code>argumentos (arguments)</code></a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions">Arrow functions</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters">Default parameters</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters">Rest parameters</a></li> +</ul> + +<h2 id="Páginas_adicionais_de_referência">Páginas adicionais de referência</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Lexical_grammar">Lexical grammar</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Data_structures">Data types and data structures</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Strict_mode">Strict mode</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Deprecated_and_obsolete_features">Deprecated features</a></li> +</ul> diff --git a/files/pt-pt/web/javascript/reference/operadores/função/index.html b/files/pt-pt/web/javascript/reference/operadores/função/index.html new file mode 100644 index 0000000000..450183b727 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/operadores/função/index.html @@ -0,0 +1,139 @@ +--- +title: Expressão função (Function expression) +slug: Web/JavaScript/Reference/Operadores/função +tags: + - Expressões Primárias + - Funiconaldiade de Linguagem + - Função + - JavaScript + - Operador +translation_of: Web/JavaScript/Reference/Operators/function +--- +<div>{{jsSidebar("Operators")}}</div> + +<p>A palavra-chave <strong><code>function</code></strong> pode ser utilziada para definir uma função dentro de uma expressão.</p> + +<p>You can also define functions using the <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function"><code>Function</code></a> constructor and a <a href="/en-US/docs/Web/JavaScript/Reference/Statements/function"><code>function declaration</code></a>.</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-functionexpression.html", "shorter")}}</div> + + + +<h2 id="Sintaxe">Sintaxe</h2> + +<pre class="syntaxbox">let <var>myFunction</var> = function [<var>name</var>]([<var>param1</var>[, <var>param2[</var>, ..., <var>paramN</var>]]]) { + <var>statements</var> +};</pre> + +<p>As of ES2015, you can also use {{jsxref("Functions/Arrow_functions", "arrow functions")}}.</p> + +<h3 id="Parâmetros">Parâmetros</h3> + +<dl> + <dt><code><var>name</var></code> {{optional_inline}}</dt> + <dd>The function name. Can be omitted, in which case the function is <em>anonymous</em>. The name is only local to the function body.</dd> + <dt><code><var>paramN</var></code> {{optional_inline}}</dt> + <dd>The name of an argument to be passed to the function.</dd> + <dt><code><var>statements</var></code> {{optional_inline}}</dt> + <dd>The statements which comprise the body of the function.</dd> +</dl> + +<h2 id="Descrição">Descrição</h2> + +<p>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 <em>function name</em>, which can be omitted in function expressions to create <em>anonymous</em> functions. A function expression can be used as an <a href="/en-US/docs/Glossary/IIFE">IIFE (Immediately Invoked Function Expression)</a> which runs as soon as it is defined. See also the chapter about {{jsxref("Functions", "functions")}} for more information.</p> + +<h3 id="Function_expression_hoisting">Function expression hoisting</h3> + +<p>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:</p> + +<pre class="brush: js">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'); +}; +</pre> + +<h3 id="Named_function_expression">Named function expression</h3> + +<p>If you want to refer to the current function inside the function body, you need to create a named function expression. <u><strong>This name is then local only to the function body (scope)</strong></u>. This also avoids using the non-standard {{jsxref("Functions/arguments/callee", "arguments.callee")}} property.</p> + +<pre class="brush: js">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; +</pre> + +<p>The variable the function expression is assigned to will have a <code>name</code> 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).</p> + +<pre class="brush: js">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) +</pre> + +<h2 id="Exemplos">Exemplos</h2> + +<p>The following example defines an unnamed function and assigns it to <code>x</code>. The function returns the square of its argument:</p> + +<pre class="brush: js">var x = function(y) { + return y * y; +}; +</pre> + +<p>More commonly it is used as a <a href="/en-US/docs/Glossary/Callback_function">callback</a>:</p> + +<pre class="brush: js">button.addEventListener('click', function(event) { + console.log('button is clicked!') +})</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificação</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('ESDraft', '#sec-function-definitions', 'Function definitions')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_de_navegador">Compatibilidade de navegador</h2> + + + +<p>{{Compat("javascript.operators.function")}}</p> + +<h2 id="Consulte_também">Consulte também </h2> + +<ul> + <li>{{jsxref("Arrow_functions", "Arrow functions")}}</li> + <li>{{jsxref("Functions_and_function_scope", "Functions and function scope")}}</li> + <li>{{jsxref("Function")}}</li> + <li>{{jsxref("Statements/function", "function statement")}}</li> + <li>{{jsxref("Statements/function*", "function* statement")}}</li> + <li>{{jsxref("Operators/function*", "function* expression")}}</li> + <li>{{jsxref("GeneratorFunction")}}</li> + <li>{{jsxref("Statements/async_function", "async function")}}</li> + <li>{{jsxref("Operators/async_function", "async function expression")}}</li> +</ul> diff --git a/files/pt-pt/web/javascript/reference/operadores/index.html b/files/pt-pt/web/javascript/reference/operadores/index.html new file mode 100644 index 0000000000..02a550b7b0 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/operadores/index.html @@ -0,0 +1,309 @@ +--- +title: Expressões e operadores +slug: Web/JavaScript/Reference/Operadores +tags: + - JavaScript + - Operadores + - Página Landing + - Resumo + - Sinopse +translation_of: Web/JavaScript/Reference/Operators +--- +<div>{{jsSidebar("Operators")}}</div> + +<p>Este capítulo documenta todos os operadores, expressões e palavras-chave da linguagem JavaScript.</p> + +<h2 id="Expressões_e_operadores_por_categoria">Expressões e operadores por categoria</h2> + +<p>For an alphabetical listing see the sidebar on the left.</p> + +<h3 id="Expressões_primárias">Expressões primárias</h3> + +<p>Basic keywords and general expressions in JavaScript.</p> + +<dl> + <dt>{{JSxRef("Operators/this", "this")}}</dt> + <dd>The <code>this</code> keyword refers to a special property of an execution context.</dd> + <dt>{{JSxRef("Operators/function", "function")}}</dt> + <dd>The <code>function</code> keyword defines a function expression.</dd> + <dt>{{JSxRef("Operators/class", "class")}}</dt> + <dd>The <code>class</code> keyword defines a class expression.</dd> + <dt>{{JSxRef("Operators/function*", "function*")}}</dt> + <dd>The <code>function*</code> keyword defines a generator function expression.</dd> + <dt>{{JSxRef("Operators/yield", "yield")}}</dt> + <dd>Pause and resume a generator function.</dd> + <dt>{{JSxRef("Operators/yield*", "yield*")}}</dt> + <dd>Delegate to another generator function or iterable object.</dd> + <dt>{{JSxRef("Operators/async_function", "async function")}}</dt> + <dd>The <code>async function</code> defines an async function expression.</dd> + <dt>{{JSxRef("Operators/await", "await")}}</dt> + <dd>Pause and resume an async function and wait for the promise's resolution/rejection.</dd> + <dt>{{JSxRef("Global_Objects/Array", "[]")}}</dt> + <dd>Array initializer/literal syntax.</dd> + <dt>{{JSxRef("Operators/Object_initializer", "{}")}}</dt> + <dd>Object initializer/literal syntax.</dd> + <dt>{{JSxRef("Global_Objects/RegExp", "/ab+c/i")}}</dt> + <dd>Regular expression literal syntax.</dd> + <dt>{{JSxRef("Operators/Grouping", "( )")}}</dt> + <dd>Grouping operator.</dd> +</dl> + +<h3 id="Expressões_Left-hand-side">Expressões "Left-hand-side"</h3> + +<p>Left values are the destination of an assignment.</p> + +<dl> + <dt>{{jsxref("Operators/Property_accessors", "Property accessors", "", 1)}}</dt> + <dd>Member operators provide access to a property or method of an object<br> + (<code>object.property</code> and <code>object["property"]</code>).</dd> + <dt>{{jsxref("Operators/new", "new")}}</dt> + <dd>The <code>new</code> operator creates an instance of a constructor.</dd> + <dt><a href="/en-US/docs/Web/JavaScript/Reference/Operators/new.target">new.target</a></dt> + <dd>In constructors, <code>new.target</code> refers to the constructor that was invoked by {{jsxref("Operators/new", "new")}}.</dd> + <dt>{{jsxref("Operators/super", "super")}}</dt> + <dd>The <code>super</code> keyword calls the parent constructor.</dd> + <dt>{{jsxref("Operators/Spread_operator", "...obj")}}</dt> + <dd>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.</dd> +</dl> + +<h3 id="Aumento_e_diminuição">Aumento e diminuição</h3> + +<p>Postfix/prefix increment and postfix/prefix decrement operators.</p> + +<dl> + <dt>{{jsxref("Operators/Arithmetic_Operators", "A++", "#Increment")}}</dt> + <dd>Postfix increment operator.</dd> + <dt>{{jsxref("Operators/Arithmetic_Operators", "A--", "#Decrement")}}</dt> + <dd>Postfix decrement operator.</dd> + <dt>{{jsxref("Operators/Arithmetic_Operators", "++A", "#Increment")}}</dt> + <dd>Prefix increment operator.</dd> + <dt>{{jsxref("Operators/Arithmetic_Operators", "--A", "#Decrement")}}</dt> + <dd>Prefix decrement operator.</dd> +</dl> + +<h3 id="Operadores_unários">Operadores unários</h3> + +<p>A unary operation is operation with only one operand.</p> + +<dl> + <dt>{{jsxref("Operators/delete", "delete")}}</dt> + <dd>The <code>delete</code> operator deletes a property from an object.</dd> + <dt>{{jsxref("Operators/void", "void")}}</dt> + <dd>The <code>void</code> operator discards an expression's return value.</dd> + <dt>{{jsxref("Operators/typeof", "typeof")}}</dt> + <dd>The <code>typeof</code> operator determines the type of a given object.</dd> + <dt>{{jsxref("Operators/Arithmetic_Operators", "+", "#Unary_plus")}}</dt> + <dd>The unary plus operator converts its operand to Number type.</dd> + <dt>{{jsxref("Operators/Arithmetic_Operators", "-", "#Unary_negation")}}</dt> + <dd>The unary negation operator converts its operand to Number type and then negates it.</dd> + <dt>{{jsxref("Operators/Bitwise_Operators", "~", "#Bitwise_NOT")}}</dt> + <dd>Bitwise NOT operator.</dd> + <dt>{{jsxref("Operators/Logical_Operators", "!", "#Logical_NOT")}}</dt> + <dd>Logical NOT operator.</dd> +</dl> + +<h3 id="Operadores_de_aritmética">Operadores de aritmética</h3> + +<p>Arithmetic operators take numerical values (either literals or variables) as their operands and return a single numerical value.</p> + +<dl> + <dt>{{jsxref("Operators/Arithmetic_Operators", "+", "#Addition")}}</dt> + <dd>Addition operator.</dd> + <dt>{{jsxref("Operators/Arithmetic_Operators", "-", "#Subtraction")}}</dt> + <dd>Subtraction operator.</dd> + <dt>{{jsxref("Operators/Arithmetic_Operators", "/", "#Division")}}</dt> + <dd>Division operator.</dd> + <dt>{{jsxref("Operators/Arithmetic_Operators", "*", "#Multiplication")}}</dt> + <dd>Multiplication operator.</dd> + <dt>{{jsxref("Operators/Arithmetic_Operators", "%", "#Remainder")}}</dt> + <dd>Remainder operator.</dd> +</dl> + +<dl> + <dt>{{JSxRef("Operators/Arithmetic_Operators", "**", "#Exponentiation")}}</dt> + <dd>Exponentiation operator.</dd> +</dl> + +<h3 id="Operadores_relacionais">Operadores relacionais</h3> + +<p>A comparison operator compares its operands and returns a <code>Boolean</code> value based on whether the comparison is true.</p> + +<dl> + <dt>{{jsxref("Operators/in", "in")}}</dt> + <dd>The <code>in</code> operator determines whether an object has a given property.</dd> + <dt>{{jsxref("Operators/instanceof", "instanceof")}}</dt> + <dd>The <code>instanceof</code> operator determines whether an object is an instance of another object.</dd> + <dt>{{jsxref("Operators/Comparison_Operators", "<", "#Less_than_operator")}}</dt> + <dd>Less than operator.</dd> + <dt>{{jsxref("Operators/Comparison_Operators", ">", "#Greater_than_operator")}}</dt> + <dd>Greater than operator.</dd> + <dt>{{jsxref("Operators/Comparison_Operators", "<=", "#Less_than_or_equal_operator")}}</dt> + <dd>Less than or equal operator.</dd> + <dt>{{jsxref("Operators/Comparison_Operators", ">=", "#Greater_than_or_equal_operator")}}</dt> + <dd>Greater than or equal operator.</dd> +</dl> + +<div class="note"> +<p><strong>Nota: =></strong> não é um operador, mas a notação para <a href="/pt-PT/docs/Web/JavaScript/Reference/Funcoes/Funcoes_seta">funções seta (<em>arrow</em></a>).</p> +</div> + +<h3 id="Operadores_de_equality">Operadores de <em>equality</em></h3> + +<p>The result of evaluating an equality operator is always of type <code>Boolean</code> based on whether the comparison is true.</p> + +<dl> + <dt>{{jsxref("Operators/Comparison_Operators", "==", "#Equality")}}</dt> + <dd>Equality operator.</dd> + <dt>{{jsxref("Operators/Comparison_Operators", "!=", "#Inequality")}}</dt> + <dd>Inequality operator.</dd> + <dt>{{jsxref("Operators/Comparison_Operators", "===", "#Identity")}}</dt> + <dd>Identity operator.</dd> + <dt>{{jsxref("Operators/Comparison_Operators", "!==", "#Nonidentity")}}</dt> + <dd>Nonidentity operator.</dd> +</dl> + +<h3 id="Bitwise_shift_operators">Bitwise shift operators</h3> + +<p>Operations to shift all bits of the operand.</p> + +<dl> + <dt>{{jsxref("Operators/Bitwise_Operators", "<<", "#Left_shift")}}</dt> + <dd>Bitwise left shift operator.</dd> + <dt>{{jsxref("Operators/Bitwise_Operators", ">>", "#Right_shift")}}</dt> + <dd>Bitwise right shift operator.</dd> + <dt>{{jsxref("Operators/Bitwise_Operators", ">>>", "#Unsigned_right_shift")}}</dt> + <dd>Bitwise unsigned right shift operator.</dd> +</dl> + +<h3 id="Operadores_de_binário_bitwise">Operadores de binário <em>bitwise</em></h3> + +<p>Bitwise operators treat their operands as a set of 32 bits (zeros and ones) and return standard JavaScript numerical values.</p> + +<dl> + <dt>{{jsxref("Operators/Bitwise_Operators", "&", "#Bitwise_AND")}}</dt> + <dd>Bitwise AND.</dd> + <dt>{{jsxref("Operators/Bitwise_Operators", "|", "#Bitwise_OR")}}</dt> + <dd>Bitwise OR.</dd> + <dt>{{jsxref("Operators/Bitwise_Operators", "^", "#Bitwise_XOR")}}</dt> + <dd>Bitwise XOR.</dd> +</dl> + +<h3 id="Operadores_de_binário_logical">Operadores de binário <em>logical</em></h3> + +<p>Logical operators are typically used with boolean (logical) values, and when they are, they return a boolean value.</p> + +<dl> + <dt>{{jsxref("Operators/Logical_Operators", "&&", "#Logical_AND")}}</dt> + <dd>Logical AND.</dd> + <dt>{{jsxref("Operators/Logical_Operators", "||", "#Logical_OR")}}</dt> + <dd>Logical OR.</dd> +</dl> + +<h3 id="Operdor_condicional_ternário">Operdor condicional (ternário)</h3> + +<dl> + <dt>{{jsxref("Operators/Conditional_Operator", "(condition ? ifTrue : ifFalse)")}}</dt> + <dd> + <p>The conditional operator returns one of two values based on the logical value of the condition.</p> + </dd> +</dl> + +<h3 id="Operadores_de_Assignment">Operadores de <em>Assignment</em></h3> + +<p>An assignment operator assigns a value to its left operand based on the value of its right operand.</p> + +<dl> + <dt>{{jsxref("Operators/Assignment_Operators", "=", "#Assignment")}}</dt> + <dd>Assignment operator.</dd> + <dt>{{jsxref("Operators/Assignment_Operators", "*=", "#Multiplication_assignment")}}</dt> + <dd>Multiplication assignment.</dd> + <dt>{{jsxref("Operators/Assignment_Operators", "/=", "#Division_assignment")}}</dt> + <dd>Division assignment.</dd> + <dt>{{jsxref("Operators/Assignment_Operators", "%=", "#Remainder_assignment")}}</dt> + <dd>Remainder assignment.</dd> + <dt>{{jsxref("Operators/Assignment_Operators", "+=", "#Addition_assignment")}}</dt> + <dd>Addition assignment.</dd> + <dt>{{jsxref("Operators/Assignment_Operators", "-=", "#Subtraction_assignment")}}</dt> + <dd>Subtraction assignment</dd> + <dt>{{jsxref("Operators/Assignment_Operators", "<<=", "#Left_shift_assignment")}}</dt> + <dd>Left shift assignment.</dd> + <dt>{{jsxref("Operators/Assignment_Operators", ">>=", "#Right_shift_assignment")}}</dt> + <dd>Right shift assignment.</dd> + <dt>{{jsxref("Operators/Assignment_Operators", ">>>=", "#Unsigned_right_shift_assignment")}}</dt> + <dd>Unsigned right shift assignment.</dd> + <dt>{{jsxref("Operators/Assignment_Operators", "&=", "#Bitwise_AND_assignment")}}</dt> + <dd>Bitwise AND assignment.</dd> + <dt>{{jsxref("Operators/Assignment_Operators", "^=", "#Bitwise_XOR_assignment")}}</dt> + <dd>Bitwise XOR assignment.</dd> + <dt>{{jsxref("Operators/Assignment_Operators", "|=", "#Bitwise_OR_assignment")}}</dt> + <dd>Bitwise OR assignment.</dd> + <dt>{{jsxref("Operators/Destructuring_assignment", "[a, b] = [1, 2]")}}<br> + {{jsxref("Operators/Destructuring_assignment", "{a, b} = {a:1, b:2}")}}</dt> + <dd> + <p>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.</p> + </dd> +</dl> + +<h3 id="Operador_de_aspas">Operador de aspas</h3> + +<dl> + <dt>{{jsxref("Operators/Comma_Operator", ",")}}</dt> + <dd>The comma operator allows multiple expressions to be evaluated in a single statement and returns the result of the last expression.</dd> +</dl> + +<h3 id="Funcionalidades_não_padrão">Funcionalidades não padrão</h3> + +<dl> + <dt>{{non-standard_inline}} {{jsxref("Operators/Legacy_generator_function", "Legacy generator function", "", 1)}}</dt> + <dd>The <code>function</code> 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.</dd> + <dt>{{non-standard_inline}} {{jsxref("Operators/Expression_closures", "Expression closures", "", 1)}}</dt> + <dd>The expression closure syntax is a shorthand for writing simple function.</dd> + <dt>{{non-standard_inline}} {{jsxref("Operators/Array_comprehensions", "[for (x of y) x]")}}</dt> + <dd>Array comprehensions.</dd> + <dt>{{non-standard_inline}} {{jsxref("Operators/Generator_comprehensions", "(for (x of y) y)")}}</dt> + <dd>Generator comprehensions.</dd> +</dl> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + <tr> + <td>{{SpecName('ES1', '#sec-11', 'Expressions')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-11', 'Expressions')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-ecmascript-language-expressions', 'ECMAScript Language: Expressions')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>New: Spread operator, destructuring assignment, <code>super</code> keyword.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-ecmascript-language-expressions', 'ECMAScript Language: Expressions')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_de_navegador">Compatibilidade de navegador</h2> + + + +<p>{{Compat("javascript.operators")}}</p> + +<h2 id="Consulte_também">Consulte também</h2> + +<ul> + <li><a href="/pt-PT/docs/Web/JavaScript/Reference/Operadores/Precedencia_operador">Precedência de operador</a></li> +</ul> diff --git a/files/pt-pt/web/javascript/reference/operadores/operador_virgula/index.html b/files/pt-pt/web/javascript/reference/operadores/operador_virgula/index.html new file mode 100644 index 0000000000..e797f92953 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/operadores/operador_virgula/index.html @@ -0,0 +1,94 @@ +--- +title: Operador Vírgula +slug: Web/JavaScript/Reference/Operadores/Operador_virgula +tags: + - Composto + - Expressão + - Funcionalidade de Linguagem + - JavaScript + - Operador + - Referencia + - Vírgula +translation_of: Web/JavaScript/Reference/Operators/Comma_Operator +--- +<div>Operador {{jsSidebar("Operators")}}</div> + +<p>O <strong>operador vírgula </strong>(<strong><code>,</code></strong>) 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 <code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/for">for</a></code> loop.</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-commaoperators.html")}}</div> + + + +<h2 id="Sintaxe">Sintaxe</h2> + +<pre class="syntaxbox"><em>expr1</em>, <em>expr2, expr3...</em></pre> + +<h3 id="Parâmetros">Parâmetros</h3> + +<dl> + <dt><code>expr1</code>, <code>expr2</code>, <code>expr3</code>...</dt> + <dd>One or more expressions, the last of which is returned as the value of the compound expression.</dd> +</dl> + +<h2 id="Notas_de_utilização">Notas de utilização</h2> + +<p>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 <code>for</code> loop.</p> + +<p>The comma operator is fully different from the comma within arrays, objects, and function arguments and parameters.</p> + +<h2 id="Exemplos">Exemplos</h2> + +<p>If <code>a</code> is a 2-dimensional array with 10 elements on each side, the following code uses the comma operator to increment <code>i</code> and decrement <code>j</code> at once.</p> + +<p>The following code prints the values of the diagonal elements in the array:</p> + +<pre class="brush:js;highlight:[1]">for (var i = 0, j = 9; i <= 9; i++, j--) + console.log('a[' + i + '][' + j + '] = ' + a[i][j]);</pre> + +<p>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, <code>a</code> is set to the value of <code>b = 3</code> (which is 3), but the <code>c = 4</code> expression still evaluates and its result returned to console (i.e., 4). This is due to <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence">operator precedence and associativity</a>.</p> + +<pre class="brush: js">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) +</pre> + +<h3 id="Processing_and_then_returning">Processing and then returning</h3> + +<p>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:</p> + +<pre class="brush: js">function myFunc() { + var x = 0; + + return (x += 1, x); // the same as return ++x; +}</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificação</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-comma-operator', 'Comma operator')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_de_navegador">Compatibilidade de navegador</h2> + + + +<p>{{Compat("javascript.operators.comma")}}</p> + +<h2 id="Consulte_também">Consulte também</h2> + +<ul> + <li>Repetição (<em>loop</em>) de <a href="/pt-PT/docs/Web/JavaScript/Reference/Extratos_e_declarações/for"><code>for</code> </a></li> +</ul> diff --git a/files/pt-pt/web/javascript/reference/operadores/precedencia_operador/index.html b/files/pt-pt/web/javascript/reference/operadores/precedencia_operador/index.html new file mode 100644 index 0000000000..03d4345410 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/operadores/precedencia_operador/index.html @@ -0,0 +1,461 @@ +--- +title: Precedência de operador +slug: Web/JavaScript/Reference/Operadores/Precedencia_operador +tags: + - Guía + - JavaScript + - precedência +translation_of: Web/JavaScript/Reference/Operators/Operator_Precedence +--- +<div>{{jsSidebar("Operators")}}</div> + +<p>A <strong>precedência de operador</strong> 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..</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-operatorprecedence.html")}}</div> + + + +<h2 id="Precedência_e_Associabilidade">Precedência e Associabilidade</h2> + +<p>Consider an expression describable by the representation below. Note that both OP<sub>1</sub> and OP<sub>2 </sub>are fill-in-the-blanks for OPerators.</p> + +<pre class="syntaxbox">a OP b OP c +</pre> + +<p>If <code>OP<sub>1</sub></code> and <code>OP<sub>2</sub></code> 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.</p> + +<pre>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 </pre> + +<p>Left-associativity (left-to-right) means that it is processed as <code>(a OP<sub>1</sub> b) OP<sub>2</sub> c</code>, while right-associativity (right-to-left) means it is interpreted as <code>a OP<sub>1</sub> (b OP<sub>2</sub> c)</code>. Assignment operators are right-associative, so you can write:</p> + +<pre>a = b = 5; // same as writing a = (b = 5); +</pre> + +<p>with the expected result that <code>a</code> and <code>b</code> get the value 5. This is because the assignment operator returns the value that is assigned. First, <code>b</code> is set to 5. Then the <code>a</code> is also set to 5, the return value of <code>b = 5</code>, aka right operand of the assignment.</p> + +<p>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.</p> + +<table> + <tbody> + <tr> + <td>Código</td> + <td>Resultado</td> + </tr> + <tr> + <td> + <pre> +function echo(name, num) { + console.log("Evaluating the " + name + " side"); + return num; +} +// Notice the division operator (/) +console.log(echo("left", 6) / echo("right", 2)); +</pre> + </td> + <td> + <pre> +Evaluating the left side +Evaluating the right side +3 +</pre> + </td> + </tr> + <tr> + <td> + <pre> +function echo(name, num) { + console.log("Evaluating the " + name + " side"); + return num; +} +// Notice the exponentiation operator (**) +console.log(echo("left", 2) ** echo("right", 3));</pre> + </td> + <td> + <pre> +Evaluating the left side +Evaluating the right side +8</pre> + </td> + </tr> + </tbody> +</table> + +<p>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.</p> + +<table> + <tbody> + <tr> + <td>Código</td> + <td>Resultado</td> + </tr> + <tr> + <td> + <pre> +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)); +</pre> + </td> + <td> + <pre> +Evaluating the left side +Evaluating the middle side +Evaluating the right side +1 +</pre> + </td> + </tr> + <tr> + <td> + <pre> +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)); +</pre> + </td> + <td> + <pre> +Evaluating the left side +Evaluating the middle side +Evaluating the right side +512 +</pre> + </td> + </tr> + <tr> + <td> + <pre> +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));</pre> + </td> + <td> + <pre> +Evaluating the left side +Evaluating the middle side +Evaluating the right side +64</pre> + </td> + </tr> + </tbody> +</table> + +<p>Looking at the code snippets above, <code>6 / 3 / 2</code> is the same as <code>(6 / 3) / 2</code> because division is left-associative. Exponentiation, on the other hand, is right-associative, so <code>2 ** 3 ** 2</code> is the same as <code>2 ** (3 ** 2)</code>. Thus, doing (<code>2 ** 3) ** 2</code> changes the order and results in the 64 seen in the table above.</p> + +<p>Remember that precedence comes before associativity. So, mixing division and exponentiation, the exponentiation comes before the division. For example, <code>2 ** 3 / 3 ** 2</code> results in 0.8888888888888888 because it is the same as <code>(2 ** 3) / (3 ** 2)</code>.</p> + +<h3 id="Note_on_Grouping_and_Short-Circuiting">Note on Grouping and Short-Circuiting</h3> + +<p>In the table below, <strong>Grouping</strong> is listed as having the highest precedence. However, that does not always mean the expression within the grouping symbols <code>( … )</code> is evaluated first, especially when it comes to short-circuiting.</p> + +<p>Short-circuiting is jargon for conditional evaluation. For example, in the expression <code>a && (b + c)</code>, if <code>a</code> is <a href="https://wiki.developer.mozilla.org/en-US/docs/Glossary/Falsy">“falsy”</a>, then the sub-expression <code>(b + c)</code> 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.</p> + +<pre>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` +</pre> + +<h2 id="Exemplos">Exemplos</h2> + +<pre>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. + +</pre> + +<h2 id="Tabela">Tabela</h2> + +<p>The following table is ordered from highest (20) to lowest (1) precedence.</p> + +<table class="fullwidth-table"> + <tbody> + <tr> + <th>Precedência</th> + <th>Tipo de operador (Operator)</th> + <th>Associatividade</th> + <th>Operadores individuais</th> + </tr> + <tr> + <td>20</td> + <td>{{jsxref("Operators/Grouping", "Grouping")}}</td> + <td>n/a</td> + <td><code>( … )</code></td> + </tr> + <tr> + <td colspan="1" rowspan="4">19</td> + <td>{{jsxref("Operators/Property_Accessors", "Member Access", "#Dot_notation")}}</td> + <td>left-to-right</td> + <td><code>… . …</code></td> + </tr> + <tr> + <td>{{jsxref("Operators/Property_Accessors", "Computed Member Access","#Bracket_notation")}}</td> + <td>left-to-right</td> + <td><code>… [ … ]</code></td> + </tr> + <tr> + <td>{{jsxref("Operators/new","new")}} (with argument list)</td> + <td>n/a</td> + <td><code>new … ( … )</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Guide/Functions">Function Call</a></td> + <td>left-to-right</td> + <td><code>… ( <var>… </var>)</code></td> + </tr> + <tr> + <td rowspan="1">18</td> + <td>{{jsxref("Operators/new","new")}} (without argument list)</td> + <td>right-to-left</td> + <td><code>new …</code></td> + </tr> + <tr> + <td rowspan="2">17</td> + <td>{{jsxref("Operators/Arithmetic_Operators","Postfix Increment","#Increment")}}</td> + <td colspan="1" rowspan="2">n/a</td> + <td><code>… ++</code></td> + </tr> + <tr> + <td>{{jsxref("Operators/Arithmetic_Operators","Postfix Decrement","#Decrement")}}</td> + <td><code>… --</code></td> + </tr> + <tr> + <td colspan="1" rowspan="10">16</td> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators#Logical_NOT">Logical NOT</a></td> + <td colspan="1" rowspan="10">right-to-left</td> + <td><code>! …</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#Bitwise_NOT">Bitwise NOT</a></td> + <td><code>~ …</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Unary_plus">Unary Plus</a></td> + <td><code>+ …</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Unary_negation">Unary Negation</a></td> + <td><code>- …</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Increment">Prefix Increment</a></td> + <td><code>++ …</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Decrement">Prefix Decrement</a></td> + <td><code>-- …</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/typeof">typeof</a></td> + <td><code>typeof …</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/void">void</a></td> + <td><code>void …</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/delete">delete</a></td> + <td><code>delete …</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/await">await</a></td> + <td><code>await …</code></td> + </tr> + <tr> + <td>15</td> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Exponentiation">Exponentiation</a></td> + <td>right-to-left</td> + <td><code>… ** …</code></td> + </tr> + <tr> + <td rowspan="3">14</td> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Multiplication">Multiplication</a></td> + <td colspan="1" rowspan="3">left-to-right</td> + <td><code>… * …</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Division">Division</a></td> + <td><code>… / …</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Remainder">Remainder</a></td> + <td><code>… % …</code></td> + </tr> + <tr> + <td rowspan="2">13</td> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Addition">Addition</a></td> + <td colspan="1" rowspan="2">left-to-right</td> + <td><code>… + …</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Subtraction">Subtraction</a></td> + <td><code>… - …</code></td> + </tr> + <tr> + <td rowspan="3">12</td> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators">Bitwise Left Shift</a></td> + <td colspan="1" rowspan="3">left-to-right</td> + <td><code>… << …</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators">Bitwise Right Shift</a></td> + <td><code>… >> …</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators">Bitwise Unsigned Right Shift</a></td> + <td><code>… >>> …</code></td> + </tr> + <tr> + <td rowspan="6">11</td> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Less_than_operator">Less Than</a></td> + <td colspan="1" rowspan="6">left-to-right</td> + <td><code>… < …</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Less_than__or_equal_operator">Less Than Or Equal</a></td> + <td><code>… <= …</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Greater_than_operator">Greater Than</a></td> + <td><code>… > …</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Greater_than_or_equal_operator">Greater Than Or Equal</a></td> + <td><code>… >= …</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/in">in</a></td> + <td><code>… in …</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/instanceof">instanceof</a></td> + <td><code>… instanceof …</code></td> + </tr> + <tr> + <td rowspan="4">10</td> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Equality">Equality</a></td> + <td colspan="1" rowspan="4">left-to-right</td> + <td><code>… == …</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Inequality">Inequality</a></td> + <td><code>… != …</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Identity">Strict Equality</a></td> + <td><code>… === …</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Nonidentity">Strict Inequality</a></td> + <td><code>… !== …</code></td> + </tr> + <tr> + <td>9</td> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#Bitwise_AND">Bitwise AND</a></td> + <td>left-to-right</td> + <td><code>… & …</code></td> + </tr> + <tr> + <td>8</td> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#Bitwise_XOR">Bitwise XOR</a></td> + <td>left-to-right</td> + <td><code>… ^ …</code></td> + </tr> + <tr> + <td>7</td> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#Bitwise_OR">Bitwise OR</a></td> + <td>left-to-right</td> + <td><code>… | …</code></td> + </tr> + <tr> + <td>6</td> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators#Logical_AND">Logical AND</a></td> + <td>left-to-right</td> + <td><code>… && …</code></td> + </tr> + <tr> + <td>5</td> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators#Logical_OR">Logical OR</a></td> + <td>left-to-right</td> + <td><code>… || …</code></td> + </tr> + <tr> + <td>4</td> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator">Conditional</a></td> + <td>right-to-left</td> + <td><code>… ? … : …</code></td> + </tr> + <tr> + <td rowspan="13">3</td> + <td rowspan="13"><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Assignment_Operators">Assignment</a></td> + <td rowspan="13">right-to-left</td> + <td><code>… = …</code></td> + </tr> + <tr> + <td><code>… += …</code></td> + </tr> + <tr> + <td><code>… -= …</code></td> + </tr> + <tr> + <td><code>… **= …</code></td> + </tr> + <tr> + <td><code>… *= …</code></td> + </tr> + <tr> + <td><code>… /= …</code></td> + </tr> + <tr> + <td><code>… %= …</code></td> + </tr> + <tr> + <td><code>… <<= …</code></td> + </tr> + <tr> + <td><code>… >>= …</code></td> + </tr> + <tr> + <td><code>… >>>= …</code></td> + </tr> + <tr> + <td><code>… &= …</code></td> + </tr> + <tr> + <td><code>… ^= …</code></td> + </tr> + <tr> + <td><code>… |= …</code></td> + </tr> + <tr> + <td rowspan="2">2</td> + <td>{{jsxref("Operators/yield", "yield")}}</td> + <td colspan="1" rowspan="2">right-to-left</td> + <td><code>yield …</code></td> + </tr> + <tr> + <td>{{jsxref("Operators/yield*", "yield*")}}</td> + <td><code>yield* …</code></td> + </tr> + <tr> + <td>1</td> + <td><a href="/pt-PT/docs/Web/JavaScript/Reference/Operadores/Operador_virgula">Vírgula / Sequência</a></td> + <td>left-to-right</td> + <td><code>… , …</code></td> + </tr> + </tbody> +</table> diff --git a/files/pt-pt/web/javascript/reference/sobre/index.html b/files/pt-pt/web/javascript/reference/sobre/index.html new file mode 100644 index 0000000000..3b2a79ac32 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/sobre/index.html @@ -0,0 +1,52 @@ +--- +title: Sobre a referência de JavaScript +slug: Web/JavaScript/Reference/Sobre +tags: + - JavaScript +translation_of: Web/JavaScript/Reference/About +--- +<div>{{JsSidebar}}</div> + +<p>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 <a href="/en-US/docs/Web/JavaScript/Guide">JavaScript guide</a>.</p> + +<p>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.</p> + +<h2 id="Onde_encontrar_informação_sobre_JavaScript">Onde encontrar informação sobre JavaScript</h2> + +<p>JavaScript documentation of core language features (pure <a href="/en-US/docs/Web/JavaScript/Language_Resources">ECMAScript</a>, for the most part) includes the following:</p> + +<ul> + <li><a href="/pt-PT/docs/Web/JavaScript/Guia">Guia de JavaScript</a></li> + <li><a href="/pt-PT/docs/Web/JavaScript/Reference">Referência JavaScript</a></li> +</ul> + +<p>If you are new to JavaScript, start with the <a href="/en-US/docs/Web/JavaScript/Guide">guide</a>. Once you have a firm grasp of the fundamentals, you can use the <a href="/en-US/docs/Web/JavaScript/Reference">reference</a> to get more details on individual objects and language constructs.</p> + +<h2 id="Estrutura_da_referência">Estrutura da referência</h2> + +<p>In the JavaScript reference you can find the following chapters:</p> + +<dl> + <dt><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects">Standard built-in objects</a></dt> + <dd>This chapter documents all the JavaScript standard built-in objects, along with their methods and properties.</dd> + <dt><a href="/en-US/docs/Web/JavaScript/Reference/Statements">Statements and declarations</a></dt> + <dd>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.</dd> + <dt><a href="/en-US/docs/Web/JavaScript/Reference/Operators">Expressions and operators</a></dt> + <dd>This chapter documents all the JavaScript language operators, expressions and keywords.</dd> + <dt><a href="/en-US/docs/Web/JavaScript/Reference/Functions">Functions</a></dt> + <dd>Chapter about JavaScript functions.</dd> + <dt><a href="/en-US/docs/Web/JavaScript/Reference/Classes">Classes</a></dt> + <dd>Chapter about JavaScript classes introduced in ECMAScript 6.</dd> + <dt><a href="/en-US/docs/Web/JavaScript/Reference/Errors">Errors</a></dt> + <dd>Chapter about specific errors, exceptions and warnings thrown by JavaScript.</dd> + <dt><a href="/en-US/docs/Web/JavaScript/New_in_JavaScript">New in JavaScript</a></dt> + <dd>Chapter about JavaScript version history.</dd> +</dl> + +<h3 id="Mais_páginas_de_referência">Mais páginas de referência</h3> + +<ul> + <li><a href="https://developer.mozilla.org/pt-PT/docs/Web/JavaScript/Reference/Funcionalidades_obsoletas">Funcionalidades obsoletas</a></li> + <li><a href="/pt-PT/docs/Web/JavaScript/Reference/Gramatica_lexical">Gramática Lexical</a></li> + <li><a href="/pt-PT/docs/Web/JavaScript/Estruturas_de_dados">Tipos de dados e estruturas de dados</a></li> +</ul> |