From 074785cea106179cb3305637055ab0a009ca74f2 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:42:52 -0500 Subject: initial commit --- .../web/javascript/reference/classes/index.html | 437 +++++++++++++++ .../javascript/reference/classes/static/index.html | 131 +++++ .../index.html" | 113 ++++ .../web/javascript/reference/errors/index.html | 31 ++ .../reference/errors/not_a_function/index.html | 172 ++++++ .../reference/errors/stmt_after_return/index.html | 77 +++ .../reference/errors/unexpected_token/index.html | 50 ++ .../bloco/index.html" | 116 ++++ .../for/index.html" | 145 +++++ .../index.html" | 150 ++++++ .../return/index.html" | 148 +++++ .../throw/index.html" | 271 ++++++++++ .../reference/funcionalidades_obsoletas/index.html | 289 ++++++++++ .../reference/funcoes/arguments/index.html | 228 ++++++++ .../reference/funcoes/funcoes_seta/index.html | 399 ++++++++++++++ .../web/javascript/reference/funcoes/index.html | 594 +++++++++++++++++++++ .../reference/funcoes/parametros_rest/index.html | 234 ++++++++ .../global_objects/array/concat/index.html | 205 +++++++ .../reference/global_objects/array/find/index.html | 210 ++++++++ .../global_objects/array/foreach/index.html | 328 ++++++++++++ .../global_objects/array/includes/index.html | 175 ++++++ .../reference/global_objects/array/index.html | 440 +++++++++++++++ .../reference/global_objects/array/join/index.html | 90 ++++ .../reference/global_objects/array/map/index.html | 366 +++++++++++++ .../reference/global_objects/array/pop/index.html | 96 ++++ .../global_objects/array/reverse/index.html | 133 +++++ .../global_objects/array/slice/index.html | 154 ++++++ .../global_objects/arraybuffer/index.html | 219 ++++++++ .../global_objects/asyncfunction/index.html | 124 +++++ .../asyncfunction/prototype/index.html | 55 ++ .../reference/global_objects/boolean/index.html | 156 ++++++ .../reference/global_objects/encodeuri/index.html | 152 ++++++ .../global_objects/function/arguments/index.html | 88 +++ .../global_objects/function/call/index.html | 164 ++++++ .../reference/global_objects/function/index.html | 192 +++++++ .../javascript/reference/global_objects/index.html | 173 ++++++ .../reference/global_objects/infinity/index.html | 69 +++ .../reference/global_objects/math/ceil/index.html | 161 ++++++ .../reference/global_objects/math/index.html | 214 ++++++++ .../reference/global_objects/number/index.html | 213 ++++++++ .../global_objects/number/isfinite/index.html | 126 +++++ .../global_objects/number/isinteger/index.html | 125 +++++ .../global_objects/number/isnan/index.html | 136 +++++ .../global_objects/number/max_value/index.html | 119 +++++ .../global_objects/number/min_value/index.html | 121 +++++ .../reference/global_objects/number/nan/index.html | 103 ++++ .../number/negative_infinity/index.html | 91 ++++ .../global_objects/number/prototype/index.html | 130 +++++ .../global_objects/number/tostring/index.html | 146 +++++ .../object/hasownproperty/index.html | 187 +++++++ .../reference/global_objects/object/index.html | 184 +++++++ .../global_objects/object/prototype/index.html | 198 +++++++ .../reference/global_objects/string/index.html | 326 +++++++++++ .../global_objects/string/indexof/index.html | 191 +++++++ .../global_objects/string/length/index.html | 125 +++++ .../global_objects/string/trim/index.html | 139 +++++ .../global_objects/symbol/hasinstance/index.html | 114 ++++ .../reference/global_objects/symbol/index.html | 458 ++++++++++++++++ files/pt-pt/web/javascript/reference/index.html | 307 +++++++++++ .../operadores/fun\303\247\303\243o/index.html" | 139 +++++ .../web/javascript/reference/operadores/index.html | 309 +++++++++++ .../operadores/operador_virgula/index.html | 94 ++++ .../operadores/precedencia_operador/index.html | 461 ++++++++++++++++ .../web/javascript/reference/sobre/index.html | 52 ++ 64 files changed, 12143 insertions(+) create mode 100644 files/pt-pt/web/javascript/reference/classes/index.html create mode 100644 files/pt-pt/web/javascript/reference/classes/static/index.html create mode 100644 "files/pt-pt/web/javascript/reference/errors/declara\303\247\303\243o_fun\303\247\303\243o_sem_nome/index.html" create mode 100644 files/pt-pt/web/javascript/reference/errors/index.html create mode 100644 files/pt-pt/web/javascript/reference/errors/not_a_function/index.html create mode 100644 files/pt-pt/web/javascript/reference/errors/stmt_after_return/index.html create mode 100644 files/pt-pt/web/javascript/reference/errors/unexpected_token/index.html create mode 100644 "files/pt-pt/web/javascript/reference/extratos_e_declara\303\247\303\265es/bloco/index.html" create mode 100644 "files/pt-pt/web/javascript/reference/extratos_e_declara\303\247\303\265es/for/index.html" create mode 100644 "files/pt-pt/web/javascript/reference/extratos_e_declara\303\247\303\265es/index.html" create mode 100644 "files/pt-pt/web/javascript/reference/extratos_e_declara\303\247\303\265es/return/index.html" create mode 100644 "files/pt-pt/web/javascript/reference/extratos_e_declara\303\247\303\265es/throw/index.html" create mode 100644 files/pt-pt/web/javascript/reference/funcionalidades_obsoletas/index.html create mode 100644 files/pt-pt/web/javascript/reference/funcoes/arguments/index.html create mode 100644 files/pt-pt/web/javascript/reference/funcoes/funcoes_seta/index.html create mode 100644 files/pt-pt/web/javascript/reference/funcoes/index.html create mode 100644 files/pt-pt/web/javascript/reference/funcoes/parametros_rest/index.html create mode 100644 files/pt-pt/web/javascript/reference/global_objects/array/concat/index.html create mode 100644 files/pt-pt/web/javascript/reference/global_objects/array/find/index.html create mode 100644 files/pt-pt/web/javascript/reference/global_objects/array/foreach/index.html create mode 100644 files/pt-pt/web/javascript/reference/global_objects/array/includes/index.html create mode 100644 files/pt-pt/web/javascript/reference/global_objects/array/index.html create mode 100644 files/pt-pt/web/javascript/reference/global_objects/array/join/index.html create mode 100644 files/pt-pt/web/javascript/reference/global_objects/array/map/index.html create mode 100644 files/pt-pt/web/javascript/reference/global_objects/array/pop/index.html create mode 100644 files/pt-pt/web/javascript/reference/global_objects/array/reverse/index.html create mode 100644 files/pt-pt/web/javascript/reference/global_objects/array/slice/index.html create mode 100644 files/pt-pt/web/javascript/reference/global_objects/arraybuffer/index.html create mode 100644 files/pt-pt/web/javascript/reference/global_objects/asyncfunction/index.html create mode 100644 files/pt-pt/web/javascript/reference/global_objects/asyncfunction/prototype/index.html create mode 100644 files/pt-pt/web/javascript/reference/global_objects/boolean/index.html create mode 100644 files/pt-pt/web/javascript/reference/global_objects/encodeuri/index.html create mode 100644 files/pt-pt/web/javascript/reference/global_objects/function/arguments/index.html create mode 100644 files/pt-pt/web/javascript/reference/global_objects/function/call/index.html create mode 100644 files/pt-pt/web/javascript/reference/global_objects/function/index.html create mode 100644 files/pt-pt/web/javascript/reference/global_objects/index.html create mode 100644 files/pt-pt/web/javascript/reference/global_objects/infinity/index.html create mode 100644 files/pt-pt/web/javascript/reference/global_objects/math/ceil/index.html create mode 100644 files/pt-pt/web/javascript/reference/global_objects/math/index.html create mode 100644 files/pt-pt/web/javascript/reference/global_objects/number/index.html create mode 100644 files/pt-pt/web/javascript/reference/global_objects/number/isfinite/index.html create mode 100644 files/pt-pt/web/javascript/reference/global_objects/number/isinteger/index.html create mode 100644 files/pt-pt/web/javascript/reference/global_objects/number/isnan/index.html create mode 100644 files/pt-pt/web/javascript/reference/global_objects/number/max_value/index.html create mode 100644 files/pt-pt/web/javascript/reference/global_objects/number/min_value/index.html create mode 100644 files/pt-pt/web/javascript/reference/global_objects/number/nan/index.html create mode 100644 files/pt-pt/web/javascript/reference/global_objects/number/negative_infinity/index.html create mode 100644 files/pt-pt/web/javascript/reference/global_objects/number/prototype/index.html create mode 100644 files/pt-pt/web/javascript/reference/global_objects/number/tostring/index.html create mode 100644 files/pt-pt/web/javascript/reference/global_objects/object/hasownproperty/index.html create mode 100644 files/pt-pt/web/javascript/reference/global_objects/object/index.html create mode 100644 files/pt-pt/web/javascript/reference/global_objects/object/prototype/index.html create mode 100644 files/pt-pt/web/javascript/reference/global_objects/string/index.html create mode 100644 files/pt-pt/web/javascript/reference/global_objects/string/indexof/index.html create mode 100644 files/pt-pt/web/javascript/reference/global_objects/string/length/index.html create mode 100644 files/pt-pt/web/javascript/reference/global_objects/string/trim/index.html create mode 100644 files/pt-pt/web/javascript/reference/global_objects/symbol/hasinstance/index.html create mode 100644 files/pt-pt/web/javascript/reference/global_objects/symbol/index.html create mode 100644 files/pt-pt/web/javascript/reference/index.html create mode 100644 "files/pt-pt/web/javascript/reference/operadores/fun\303\247\303\243o/index.html" create mode 100644 files/pt-pt/web/javascript/reference/operadores/index.html create mode 100644 files/pt-pt/web/javascript/reference/operadores/operador_virgula/index.html create mode 100644 files/pt-pt/web/javascript/reference/operadores/precedencia_operador/index.html create mode 100644 files/pt-pt/web/javascript/reference/sobre/index.html (limited to 'files/pt-pt/web/javascript/reference') 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 +--- +
{{JsSidebar("Classes")}}
+ +

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

+ +

Definição de classes

+ +

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

+ +

Declaração de classes

+ +

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

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

Hoisting

+ +

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

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

Expressão de Classe

+ +

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

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

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

+
+ +

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

+ +

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

+ +

Strict mode - modo estrito

+ +

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

+ +

Construtor (constructor)

+ +

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

+ +

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

+ +

Métodos de Prototype 

+ +

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

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

Métodos estáticos

+ +

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

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

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

+ +

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

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

 

+ +

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

+ +

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

+ +

 

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

Propriedades de instância

+ +

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

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

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

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

Declaração de campos (Field)

+ +
+

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

+
+ +

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

+ +

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

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

 

+ +

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

+ +

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

+ +

 

+ +

Declaração de campos (field) privados 

+ +

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

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

 

+ +

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

+ +
+

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

+
+ +

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

+ +

 

+ +

 

+ +

 

+ +

 

+ +

 

+ +

 

+ +

Derivação de classes com extends

+ +

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

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

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

+ +

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

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

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

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

Espécies

+ +

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

+ +

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

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

Chamadas à super classe com super

+ +

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

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

Mix-ins

+ +

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

+ +

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

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

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

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

Especificações

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

Compatibilidade no Browser 

+ + + +

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

+ +

Executar no Scratchpad

+ +

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

+ +

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

+ +

Veja também

+ + diff --git a/files/pt-pt/web/javascript/reference/classes/static/index.html b/files/pt-pt/web/javascript/reference/classes/static/index.html 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 +--- +
{{jsSidebar("Classes")}}
+ +

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

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

Síntaxe

+ +
static nomeDoMetodo() { ... }
+ +

Descrição

+ +

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

+ +

Como chamar métodos estáticos

+ +

Noutro método estático

+ +

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

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

No construtor de classe e noutros métodos

+ +

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

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

Exemplos

+ +

Os seguintes exemplos demonstram:

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

Especificações

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

Compatibilidade de browsers

+ + + +

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

+ +

Ver também

+ + diff --git "a/files/pt-pt/web/javascript/reference/errors/declara\303\247\303\243o_fun\303\247\303\243o_sem_nome/index.html" "b/files/pt-pt/web/javascript/reference/errors/declara\303\247\303\243o_fun\303\247\303\243o_sem_nome/index.html" new file mode 100644 index 0000000000..a747257379 --- /dev/null +++ "b/files/pt-pt/web/javascript/reference/errors/declara\303\247\303\243o_fun\303\247\303\243o_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 +--- +
{{jsSidebar("Errors")}}
+ +

Mensagem

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

Tipo de erro

+ +

{{jsxref("SyntaxError")}}

+ +

O que correu mal?

+ +

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

+ +

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

+ +

Exemplos

+ +

Declarações vs Expressões

+ +

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

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

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

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

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

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

Funções com nome

+ +

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

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

O código seguinte irá funcionar por exemplo:

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

Métodos de objectos

+ +

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

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

Sintaxe de Callback

+ +

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

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

:

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

Veja também

+ + diff --git a/files/pt-pt/web/javascript/reference/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 +--- +

{{jsSidebar("Errors")}}

+ +

Below, you'll find a list of errors which are thrown by JavaScript. These errors can be a helpful debugging aid, but the reported problem isn't always immediately clear. The pages below will provide additional details about these errors. Each error is an object based upon the {{jsxref("Error")}} object, and has a name and a message.

+ +

Errors displayed in the Web console may include a link to the corresponding page below to help you quickly comprehend the problem in your code.

+ +

List of errors

+ +

In this list, each page is listed by name (the type of error) and message (a more detailed human-readable error message). Together, these two properties provide a starting point toward understanding and resolving the error. For more information, follow the links below!

+ +

{{ListSubPages("/en-US/docs/Web/JavaScript/Reference/Errors")}}

+ +

See also

+ + diff --git a/files/pt-pt/web/javascript/reference/errors/not_a_function/index.html b/files/pt-pt/web/javascript/reference/errors/not_a_function/index.html 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 +--- +
{{jsSidebar("Errors")}}
+ +

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

+ +

Mensagem

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

Tipo de erro

+ +

{{jsxref("TypeError")}}

+ +

O que deu errado?

+ +

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

+ +

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

+ +

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

+ + + +

Exemplos

+ +

Um erro no nome da função

+ +

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

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

O nome correto da função é getElementById:

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

Função é chamada no objeto errado

+ +

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

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

Use antes uma matriz:

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

Function shares a name with a pre-existing property

+ +

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

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

Use um nome diferente para a propriedade:

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

Usar parênteses para multiplicação

+ +

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

+ +

Usar a última forma dá um erro:

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

Pode corrigir o erro com a operadora *:

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

Importar o modulo exportado corretamente

+ +

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

+ +

Um exemplo de uma biblioteca helper (helpers.js)

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

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

+ +
import helpers from './helpers'
+ +

Ver também

+ + diff --git a/files/pt-pt/web/javascript/reference/errors/stmt_after_return/index.html b/files/pt-pt/web/javascript/reference/errors/stmt_after_return/index.html 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 +--- +
{{jsSidebar("Errors")}}
+ +

Mensagem

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

Tipo de ErroEdit

+ +

Aviso

+ +

O que correu mal?Edit

+ +

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

+ + + +

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

+ +

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

+ +

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

+ + + +

Exemplos

+ +

Casos inválidos

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

Casos válidos

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

Consulte tambémEdit

+ + diff --git a/files/pt-pt/web/javascript/reference/errors/unexpected_token/index.html b/files/pt-pt/web/javascript/reference/errors/unexpected_token/index.html 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 +--- +
{{jsSidebar("Errors")}}
+ +

Mensagem

+ +
SyntaxError: expected expression, got "x"
+SyntaxError: expected property name, got "x"
+SyntaxError: expected target, got "x"
+SyntaxError: expected rest argument name, got "x"
+SyntaxError: expected closing parenthesis, got "x"
+SyntaxError: expected '=>' after argument list, got "x"
+
+ +

Tipo de erro

+ +

{{jsxref("SyntaxError")}}

+ +

O que aconteceu de errado?

+ +

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

+ +

Exemplos

+ +

Expressão esperada

+ +

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

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

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

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

Veja também

+ + diff --git "a/files/pt-pt/web/javascript/reference/extratos_e_declara\303\247\303\265es/bloco/index.html" "b/files/pt-pt/web/javascript/reference/extratos_e_declara\303\247\303\265es/bloco/index.html" new file mode 100644 index 0000000000..a3104dbeae --- /dev/null +++ "b/files/pt-pt/web/javascript/reference/extratos_e_declara\303\247\303\265es/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 +--- +
Bloco {{jsSidebar("Statements")}}
+ +

Uma declaralção bloco (ou declaração composto em outras linguagens) é utilizada para agrupar zero ou mais declarações. O bloco é delimitado por um par de chavetas (“chavetas { }”) e opcionalmente poderá ser {{jsxref("Statements/label", "labelled", "", 1)}}:

+ +
{{EmbedInteractiveExample("pages/js/statement-block.html", "taller")}}
+ + + +

Sintaxe

+ +

Declaração de Bloco

+ +
{
+  StatementList
+}
+
+ +

Declaração de Bloco Etiquetado

+ +
LabelIdentifier: {
+  StatementList
+}
+
+ +
+
StatementList
+
Statements grouped within the block statement.
+
LabelIdentifier
+
An optional {{jsxref("Statements/label", "label", "", 1)}} for visual identification or as a target for {{jsxref("Statements/break", "break")}}.
+
+ +

Descrição

+ +

The block statement is often called compound statement in other languages. It allows you to use multiple statements where JavaScript expects only one statement. Combining statements into blocks is a common practice in JavaScript. The opposite behavior is possible using an empty statement, where you provide no statement, although one is required.

+ +

Blocks are commonly used in association with {{jsxref("Statements/if...else", "if...else")}} and {{jsxref("Statements/for", "for")}} statements.

+ +

Block Scoping Rules

+ +

With var or function declaration in non-strict mode

+ +

Variables declared with var or created by function declarations in non-strict mode do not have block scope. Variables introduced within a block are scoped to the containing function or script, and the effects of setting them persist beyond the block itself. In other words, block statements do not introduce a scope. For example:

+ +
var x = 1;
+{
+  var x = 2;
+}
+console.log(x); // logs 2
+
+ +

This logs 2 because the var x statement within the block is in the same scope as the var x statement before the block.

+ +

In non-strict code, function declarations inside blocks behave strangely. Do not use them.

+ +

With let, const or function declaration in strict mode

+ +

By contrast, identifiers declared with {{jsxref("Statements/let", "let")}} and {{jsxref("Statements/const", "const")}} do have block scope:

+ +
let x = 1;
+{
+  let x = 2;
+}
+console.log(x); // logs 1
+ +

The x = 2 is limited in scope to the block in which it was defined.

+ +

The same is true of const:

+ +
const c = 1;
+{
+  const c = 2;
+}
+console.log(c); // logs 1 and does not throw SyntaxError...
+ +

Note that the block-scoped const c = 2 does not throw a SyntaxError: Identifier 'c' has already been declared because it can be declared uniquely within the block.

+ +

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

+ +

Especificações

+ + + + + + + + + + + + +
Especificação
{{SpecName('ESDraft', '#sec-block', 'Block statement')}}
+ +

Compatibilidade de navegador

+ + + +

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

+ +

Consulte também

+ + diff --git "a/files/pt-pt/web/javascript/reference/extratos_e_declara\303\247\303\265es/for/index.html" "b/files/pt-pt/web/javascript/reference/extratos_e_declara\303\247\303\265es/for/index.html" new file mode 100644 index 0000000000..ac7586e98b --- /dev/null +++ "b/files/pt-pt/web/javascript/reference/extratos_e_declara\303\247\303\265es/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 +--- +
{{jsSidebar("Statements")}}
+ +

A declaração "for" cria uma repetição (loop) que consiste de três expressões opcionais, entre parênteses e separados por ponto e vírgula, seguido de uma declaração (normalmente bdeclaraçãod e bloco (block)) para ser executada na repetição.

+ +
{{EmbedInteractiveExample("pages/js/statement-for.html")}}
+ + + +

Sintaxe

+ +
for ([initialization]; [condition]; [final-expression])
+   statement
+ +
+
initialization
+
An expression (including assignment expressions) or variable declaration evaluated once before the loop begins. Typically used to initialize a counter variable. This expression may optionally declare new variables with var or let keywords. Variables declared with var are not local to the loop, i.e. they are in the same scope the for loop is in. Variables declared with let are local to the statement.
+
The result of this expression is discarded.
+
condition
+
An expression to be evaluated before each loop iteration. If this expression evaluates to true, statement is executed. This conditional test is optional. If omitted, the condition always evaluates to true. If the expression evaluates to false, execution skips to the first expression following the for construct.
+
final-expression
+
An expression to be evaluated at the end of each loop iteration. This occurs before the next evaluation of condition. Generally used to update or increment the counter variable.
+
statement
+
A statement that is executed as long as the condition evaluates to true. To execute multiple statements within the loop, use a {{jsxref("Statements/block", "block", "", 0)}} statement ({ ... }) to group those statements. To execute no statement within the loop, use an {{jsxref("Statements/empty", "empty", "", 0)}} statement (;).
+
+ +

Exemplos

+ +

Using for

+ +

The following for statement starts by declaring the variable i and initializing it to 0. It checks that i is less than nine, performs the two succeeding statements, and increments i by 1 after each pass through the loop.

+ +
for (let i = 0; i < 9; i++) {
+   console.log(i);
+   // more statements
+}
+
+ +

Optional for expressions

+ +

All three expressions in the head of the for loop are optional.

+ +

For example, in the initialization block it is not required to initialize variables:

+ +
var i = 0;
+for (; i < 9; i++) {
+    console.log(i);
+    // more statements
+}
+
+ +

Like the initialization block, the condition block is also optional. If you are omitting this expression, you must make sure to break the loop in the body in order to not create an infinite loop.

+ +
for (let i = 0;; i++) {
+   console.log(i);
+   if (i > 3) break;
+   // more statements
+}
+ +

You can also omit all three blocks. Again, make sure to use a {{jsxref("Statements/break", "break")}} statement to end the loop and also modify (increase) a variable, so that the condition for the break statement is true at some point.

+ +
var i = 0;
+
+for (;;) {
+  if (i > 3) break;
+  console.log(i);
+  i++;
+}
+
+ +

Using for without a statement

+ +

The following for cycle calculates the offset position of a node in the final-expression section, and therefore it does not require the use of a statement section, a semicolon is used instead.

+ +
function showOffsetPos(sId) {
+
+  var nLeft = 0, nTop = 0;
+
+  for (
+
+    var oItNode = document.getElementById(sId); /* initialization */
+
+    oItNode; /* condition */
+
+    nLeft += oItNode.offsetLeft, nTop += oItNode.offsetTop, oItNode = oItNode.offsetParent /* final-expression */
+
+  ); /* semicolon */
+
+  console.log('Offset position of \'' + sId + '\' element:\n left: ' + nLeft + 'px;\n top: ' + nTop + 'px;');
+
+}
+
+/* Example call: */
+
+showOffsetPos('content');
+
+// Output:
+// "Offset position of "content" element:
+// left: 0px;
+// top: 153px;"
+ +
Note: This is one of the few cases in JavaScript where the semicolon is mandatory. Indeed, without the semicolon the line that follows the cycle declaration will be considered a statement.
+ +

Especificações

+ + + + + + + + + + +
Especificação
{{SpecName('ESDraft', '#sec-for-statement', 'for statement')}}
+ +

Compatibilidade de navegador

+ + + +

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

+ +

Consulte também

+ + diff --git "a/files/pt-pt/web/javascript/reference/extratos_e_declara\303\247\303\265es/index.html" "b/files/pt-pt/web/javascript/reference/extratos_e_declara\303\247\303\265es/index.html" new file mode 100644 index 0000000000..af841906a1 --- /dev/null +++ "b/files/pt-pt/web/javascript/reference/extratos_e_declara\303\247\303\265es/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 +--- +
{{jsSidebar("Statements")}}
+ +

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

+ +

Declarações e instruções por categoria

+ +

For an alphabetical listing see the sidebar on the left.

+ +

Controlo de Fluxo

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

Declarações

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

Funções e classes

+ +
+
{{jsxref("Statements/function", "function")}}
+
Declara as funções com parâmetros especificados.
+
{{jsxref("Statements/function*", "function*")}}
+
Generators functions enable writing iterators more easily.
+
{{jsxref("Statements/async_function", "async function")}}
+
Declares an async function with the specified parameters.
+
{{jsxref("Statements/return", "return")}}
+
Specifies the value to be returned by a function.
+
{{jsxref("Statements/class", "class")}}
+
Declara uma Classe.
+
+ +

Iterações

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

Outros

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

Especificações

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

Compatibilidade de navegador

+ + + +

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

+ +

Consultar também

+ + diff --git "a/files/pt-pt/web/javascript/reference/extratos_e_declara\303\247\303\265es/return/index.html" "b/files/pt-pt/web/javascript/reference/extratos_e_declara\303\247\303\265es/return/index.html" new file mode 100644 index 0000000000..6cec134992 --- /dev/null +++ "b/files/pt-pt/web/javascript/reference/extratos_e_declara\303\247\303\265es/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 +--- +
{{jsSidebar("Statements")}}
+ +

The return statement ends function execution and specifies a value to be returned to the function caller.

+ +

Sintaxe

+ +
return [[expression]]; 
+ +
+
expression
+
The expression whose value is to be returned. If omitted, undefined is returned instead.
+
+ +

Descrição

+ +

When a return statement is used in a function body, the execution of the function is stopped. If specified, a given value is returned to the function caller. For example, the following function returns the square of its argument, x, where x is a number.

+ +
function square(x) {
+   return x * x;
+}
+var demo = square(3);
+// demo will equal 9
+
+ +

If the value is omitted, undefined is returned instead.

+ +

The following return statements all break the function execution:

+ +
return;
+return true;
+return false;
+return x;
+return x + y / 3;
+
+ +

Inserção Automática de Ponto e Vírgula

+ +

The return statement is affected by automatic semicolon insertion (ASI). No line terminator is allowed between the return keyword and the expression.

+ +
return
+a + b;
+
+ +

is transformed by ASI into:

+ +
return;
+a + b;
+
+ +

The console will warn "unreachable code after return statement".

+ +
Starting with Gecko 40 {{geckoRelease(40)}}, a warning is shown in the console if unreachable code is found after a return statement.
+ +

Exemplos

+ +

Interromper uma função

+ +

A function immediately stops at the point where return is called.

+ +
function counter() {
+  for (var count = 1; ; count++) {  // infinite loop
+    console.log(count + 'A'); // until 5
+      if (count === 5) {
+        return;
+      }
+      console.log(count + 'B');  // until 4
+    }
+  console.log(count + 'C');  // never appears
+}
+
+counter();
+
+// Output:
+// 1A
+// 1B
+// 2A
+// 2B
+// 3A
+// 3B
+// 4A
+// 4B
+// 5A
+
+ +

Devolver uma função

+ +

See also the article about Closures.

+ +
function magic(x) {
+  return function calc(x) { return x * 42; };
+}
+
+var answer = magic();
+answer(1337); // 56154
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition.
{{SpecName('ES5.1', '#sec-12.9', 'Return statement')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-return-statement', 'Return statement')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-return-statement', 'Return statement')}}{{Spec2('ESDraft')}} 
+ +

Compatibilidade de navegador

+ + + +

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

+ +

Consulte também

+ + diff --git "a/files/pt-pt/web/javascript/reference/extratos_e_declara\303\247\303\265es/throw/index.html" "b/files/pt-pt/web/javascript/reference/extratos_e_declara\303\247\303\265es/throw/index.html" new file mode 100644 index 0000000000..9e7a8bf54e --- /dev/null +++ "b/files/pt-pt/web/javascript/reference/extratos_e_declara\303\247\303\265es/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 +--- +
{{jsSidebar("Statements")}}
+ +

A declaração throw lança uma exeção definida pelo utilizador. A execução da função atual irá parar (os comandos depois de throw não serão executados), e o controle será passado para o primeiro bloco catch no conjunto de chamadas. Se não existir nenhum bloco catch entre as funções de caller, o programa irá terminar.

+ +

Sintaxe

+ +
expressão throw; 
+ +
+
expressão
+
A expressão para throw.
+
+ +

Descrição

+ +

Use the throw statement to throw an exception. When you throw an exception, expression specifies the value of the exception. Each of the following throws an exception:

+ +
throw 'Error2'; // generates an exception with a string value
+throw 42;       // generates an exception with the value 42
+throw true;     // generates an exception with the value true
+ +

Also note that the throw statement is affected by automatic semicolon insertion (ASI) as no line terminator between the throw keyword and the expression is allowed.

+ +

Exemplos

+ +

Throw um objeto

+ +

You can specify an object when you throw an exception. You can then reference the object's properties in the catch block. The following example creates an object of type UserException and uses it in a throw statement.

+ +
function UserException(message) {
+   this.message = message;
+   this.name = 'UserException';
+}
+function getMonthName(mo) {
+   mo = mo - 1; // Adjust month number for array index (1 = Jan, 12 = Dec)
+   var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul',
+      'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
+   if (months[mo] !== undefined) {
+      return months[mo];
+   } else {
+      throw new UserException('InvalidMonthNo');
+   }
+}
+
+try {
+   // statements to try
+   var myMonth = 15; // 15 is out of bound to raise the exception
+   var monthName = getMonthName(myMonth);
+} catch (e) {
+   monthName = 'unknown';
+   console.log(e.message, e.name); // pass exception object to err handler
+}
+
+ +

Outro exemplo de throwing um objeto

+ +

The following example tests an input string for a U.S. zip code. If the zip code uses an invalid format, the throw statement throws an exception by creating an object of type ZipCodeFormatException.

+ +
/*
+ * Creates a ZipCode object.
+ *
+ * Accepted formats for a zip code are:
+ *    12345
+ *    12345-6789
+ *    123456789
+ *    12345 6789
+ *
+ * If the argument passed to the ZipCode constructor does not
+ * conform to one of these patterns, an exception is thrown.
+ */
+
+function ZipCode(zip) {
+   zip = new String(zip);
+   pattern = /[0-9]{5}([- ]?[0-9]{4})?/;
+   if (pattern.test(zip)) {
+      // zip code value will be the first match in the string
+      this.value = zip.match(pattern)[0];
+      this.valueOf = function() {
+         return this.value
+      };
+      this.toString = function() {
+         return String(this.value)
+      };
+   } else {
+      throw new ZipCodeFormatException(zip);
+   }
+}
+
+function ZipCodeFormatException(value) {
+   this.value = value;
+   this.message = 'does not conform to the expected format for a zip code';
+   this.toString = function() {
+      return this.value + this.message;
+   };
+}
+
+/*
+ * This could be in a script that validates address data
+ * for US addresses.
+ */
+
+const ZIPCODE_INVALID = -1;
+const ZIPCODE_UNKNOWN_ERROR = -2;
+
+function verifyZipCode(z) {
+   try {
+      z = new ZipCode(z);
+   } catch (e) {
+      if (e instanceof ZipCodeFormatException) {
+         return ZIPCODE_INVALID;
+      } else {
+         return ZIPCODE_UNKNOWN_ERROR;
+      }
+   }
+   return z;
+}
+
+a = verifyZipCode(95060);         // returns 95060
+b = verifyZipCode(9560);          // returns -1
+c = verifyZipCode('a');           // returns -1
+d = verifyZipCode('95060');       // returns 95060
+e = verifyZipCode('95060 1234');  // returns 95060 1234
+
+ +

Rethrow uma exceção

+ +

You can use throw to rethrow an exception after you catch it. The following example catches an exception with a numeric value and rethrows it if the value is over 50. The rethrown exception propagates up to the enclosing function or to the top level so that the user sees it.

+ +
try {
+   throw n; // throws an exception with a numeric value
+} catch (e) {
+   if (e <= 50) {
+      // statements to handle exceptions 1-50
+   } else {
+      // cannot handle this exception, so rethrow
+      throw e;
+   }
+}
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.4
{{SpecName('ES5.1', '#sec-12.13', 'throw statement')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-throw-statement', 'throw statement')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-throw-statement', 'throw statement')}}{{Spec2('ESDraft')}} 
+ +

Compatibilidade de navegador

+ + + +

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

+ +

Consulte também

+ + + +
+ + + + + +
diff --git a/files/pt-pt/web/javascript/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 +--- +
{{JsSidebar("More")}}
+ +

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

+ +

Funcionalidades obsoletas

+ +

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

+ +

Propriedades de RegExp

+ +

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

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

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

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

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

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

Métodos de egExp

+ + + +

Propriedades de Function

+ + + +

Gerador de Legacy

+ + + +

Iterator

+ + + +

Métodos de Object

+ + + +

Métodos de Date

+ + + +

Functions

+ + + +

Proxy

+ + + +

Sequências de Escape

+ + + +

Métodos de String

+ + + +

Funcionalidades removidas

+ +

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

+ +

Object

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

Function

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

Array

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

Number

+ + + +

ParallelArray

+ + + +

Statements

+ + + +

E4X

+ +

See E4X for more information.

+ +

Variáveis Sharp

+ +

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

diff --git a/files/pt-pt/web/javascript/reference/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 +--- +

{{JSSidebar("Functions")}}

+ +

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

+ +
+

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

+
+ +
+

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

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

Sintaxe

+ +
arguments
+ +

Descrição

+ +

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

+ +

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

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

Each argument can also be set or reassigned:

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

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

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

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

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

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

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

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

+ +

Utilizar typeof com Arguments

+ +

The typeof operator returns 'object' when used with arguments

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

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

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

Propriedades

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

Exemplos

+ +

Definir uma function que concatena várias strings

+ +

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

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

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

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

Definir uma function que cria listas HTML

+ +

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

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

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

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

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

+ +

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

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

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

+ +

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

+ +
+

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

+
+ +

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

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

And also:

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

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

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

E também:

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

E também:

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

Especificações

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

Compatibildiade de navegador

+ + + +

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

+ +

Consulte também

+ + diff --git a/files/pt-pt/web/javascript/reference/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 +--- +
{{jsSidebar("Functions")}}
+ +

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

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

Sintaxe

+ +

Basic syntax

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

Advanced syntax

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

Descrição

+ +

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

+ +

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

+ +

Funções curtas

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

No separate this

+ +

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

+ + + +

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

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

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

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

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

+ +

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

+ +

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

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

Relation with strict mode

+ +

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

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

All other strict mode rules apply normally.

+ +

Invoked through call or apply

+ +

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

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

No binding of arguments

+ +

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

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

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

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

Arrow functions used as methods

+ +

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

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

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

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

Use of the new operator

+ +

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

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

Use of prototype property

+ +

Arrow functions do not have a prototype property.

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

Use of the yield keyword

+ +

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

+ +

Function body

+ +

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

+ +

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

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

Returning object literals

+ +

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

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

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

+ +

You must wrap the object literal in parentheses:

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

Line breaks

+ +

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

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

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

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

Parsing order

+ +

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

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

More examples

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

Specifications

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

Browser compatibility

+ +
+ + +

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

+
+ +

See also

+ + diff --git a/files/pt-pt/web/javascript/reference/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 +--- +
{{jsSidebar("Functions")}}
+ +

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

+ +

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

+ +

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

+ +

Descrição

+ +

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

+ +

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

+ +

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

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

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

+ +

Definindo funções

+ +

There are several ways to define functions:

+ +

The function declaration (function statement)

+ +

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

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

The function expression (function expression)

+ +

A function expression is similar to and has the same syntax as a function declaration (see function expression for details). A function expression may be a part of a larger expression. One can define "named" function expressions (where the name of the expression might be used in the call stack for example) or "anonymous" function expressions. Function expressions are not hoisted onto the beginning of the scope, therefore they cannot be used before they appear in the code.

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

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

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

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

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

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

+ +

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

+ +

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

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

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

+ +

The generator function declaration (function* statement)

+ +

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

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

The generator function expression (function* expression)

+ +

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

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

The arrow function expression (=>)

+ +

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

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

The Function constructor

+ +
+

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

+
+ +

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

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

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

+ +

The GeneratorFunction constructor

+ +
+

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

+
+ +
+

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

+
+ +

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

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

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

+ +

Parâmetros de função

+ +

Parâmetros predefinidos

+ +

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

+ +

Parâmetros Rest

+ +

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

+ +

O objeto arguments

+ +

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

+ + + +

Definindo funções de método

+ +

Getter and setter functions

+ +

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

+ +
+
get
+
+

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

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

Method definition syntax

+ +

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

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

Constructor vs. declaration vs. expression

+ +

Compare the following:

+ +

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

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

A function declaration of a function named multiply:

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

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

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

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

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

Differences

+ +

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

+ +

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

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

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

+ +

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

+ +

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

+ +

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

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

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

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

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

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

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

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

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

+ +

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

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

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

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

Examples

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

Block-level functions

+ +

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

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

Block-level functions in non-strict code

+ +

In a word: Don't.

+ +

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

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

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

+ +

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

+ +

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

+ +
var zero;
+if (shouldDefineZero) {
+   zero = function() {
+      console.log("This is zero.");
+   };
+}
+
+ +

Exemplos

+ +

Returning a formatted number

+ +

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

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

The following statements call the padZeros function.

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

Determining whether a function exists

+ +

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

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

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

+ +

Especificações

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

Compatibilidade de navegador

+ + + +

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

+ +

Consulte também

+ + diff --git a/files/pt-pt/web/javascript/reference/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 +--- +
Parâmetrois {{jsSidebar("Functions")}}
+ +

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

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

Sintaxe

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

Descrição

+ +

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

+ +

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

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

Difference between rest parameters and the arguments object

+ +

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

+ + + +

From arguments to an array

+ +

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

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

Destructuring rest parameters

+ +

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

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

Fixme

+ +

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

+ +

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

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

Exemplos

+ +

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

+ +

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Especificações

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

Compatibildiade de navegador

+ + + +

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

+ +

Consulte também

+ + diff --git a/files/pt-pt/web/javascript/reference/global_objects/array/concat/index.html b/files/pt-pt/web/javascript/reference/global_objects/array/concat/index.html 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 +--- +
{{JSRef}}
+ +

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

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

Sintaxe

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

Parâmetros

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

Valor devolvido

+ +

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

+ +

Descrição

+ +

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

+ +

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

+ + + +
+

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

+
+ +

Exemplos

+ +

Concatenar dois vectores

+ +

O código que se segue concatena dois vectores:

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

Concatenar três vectores

+ +

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

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

Concatenar valores para um vector

+ +

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

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

Concatenar vectores inclusos

+ +

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

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

Especificações

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

Browser compatibility

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

See also

+ + diff --git a/files/pt-pt/web/javascript/reference/global_objects/array/find/index.html b/files/pt-pt/web/javascript/reference/global_objects/array/find/index.html 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 +--- +
{{JSRef}}
+ +

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

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

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

+ +

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

+ +

Sintaxe

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

Parâmetros

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

Valor de retorno

+ +

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

+ +

Descrição

+ +

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

+ +

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

+ +

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

+ +

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

+ +

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

+ +

Exemplos

+ +

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

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

Encontrar um número primo num array

+ +

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

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

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

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

Polyfill

+ +

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

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

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

+ +

Especificações

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

Compatibilidade de Browsers

+ +
+ + +

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

+
+ +

Ver também

+ + diff --git a/files/pt-pt/web/javascript/reference/global_objects/array/foreach/index.html b/files/pt-pt/web/javascript/reference/global_objects/array/foreach/index.html 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 +--- +
{{JSRef}}
+ +

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

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

Sintaxe

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

Parâmetros

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

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

+
+
+ +

Valor devolvido

+ +

{{jsxref("undefined")}}.

+ +

Descrição

+ +

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

+ +

callback é invocado com três argumentos:

+ + + +

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

+ +

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

+ +

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

+ +

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

+ +
+

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

+ +

Early termination may be accomplished with:

+ + + +

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

+
+ +

Examples

+ +

Converting a for loop to forEach

+ +

before

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

after

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

 

+ +

Printing the contents of an Array Object

+ +

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

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

 

+ +

 

+ +

 

+ +

Printing the contents of an array

+ +

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

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

Using thisArg

+ +

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

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

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

+ +
+

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

+
+ +

An object copy function

+ +

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

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

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

+ +

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

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

Polyfill

+ +

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

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

Specifications

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

Browser compatibility

+ +
+ + +

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

+
+ +

See also

+ + diff --git a/files/pt-pt/web/javascript/reference/global_objects/array/includes/index.html b/files/pt-pt/web/javascript/reference/global_objects/array/includes/index.html 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 +--- +
{{JSRef}}
+ +

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

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

Syntax

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

Parameters

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

Return value

+ +

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

+ +

Examples

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

fromIndex is greater than or equal to the array length

+ +

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

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

Computed index is less than 0

+ +

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

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

includes() used as a generic method

+ +

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

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

Polyfill

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

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

+ +

Specifications

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

Browser compatibility

+ +
+ + +

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

+
+ +

See also

+ + diff --git a/files/pt-pt/web/javascript/reference/global_objects/array/index.html b/files/pt-pt/web/javascript/reference/global_objects/array/index.html 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 +--- +
{{JSRef}}
+ +

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

+ +

Descrição

+ +

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

+ +

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

+ +

Criar uma Array

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

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

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

Loop over an Array

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

Adicionar um item ao fim da Array

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

Remover um item do fim da Array

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

Remover um item do início da Array

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

Adicionar um item ao início da Array

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

Encontrar o índice dum item na Array

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

Remover um item pela posição do índice

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

Remover items pela posição do índice

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

Copiar uma Array

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

Como aceder a elementos da array

+ +

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

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

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

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

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

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

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

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

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

+ +
var promise = {
+  'var'  : 'text',
+  'array': [1, 2, 3, 4]
+};
+
+console.log(promise['var']);
+
+ +

Relationship between length and numerical properties

+ +

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

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

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

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

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

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

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

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

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

+ +

Creating an array using the result of a match

+ +

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

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

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

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

Properties

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

Methods

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

Array instances

+ +

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

+ +

Properties

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

Methods

+ +

Mutator methods

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

Accessor methods

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

Iteration methods

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

Array generic methods

+ +
+

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

+
+ +

Sometimes you would like to apply array methods to strings or other array-like objects (such as function {{jsxref("Functions/arguments", "arguments", "", 1)}}). By doing this, you treat a string as an array of characters (or otherwise treat a non-array as an array). For example, in order to check that every character in the variable str is a letter, you would write:

+ +
function isLetter(character) {
+  return character >= 'a' && character <= 'z';
+}
+
+if (Array.prototype.every.call(str, isLetter)) {
+  console.log("The string '" + str + "' contains only letters!");
+}
+
+ +

This notation is rather wasteful and JavaScript 1.6 introduced a generic shorthand:

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

{{jsxref("Global_Objects/String", "Generics", "#String_generic_methods", 1)}} are also available on {{jsxref("String")}}.

+ +

These are not part of ECMAScript standards and they are not supported by non-Gecko browsers. As a standard alternative, you can convert your object to a proper array using {{jsxref("Array.from()")}}; although that method may not be supported in old browsers:

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

Examples

+ +

Creating an array

+ +

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

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

Creating a two-dimensional array

+ +

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

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

Here is the output:

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

Using an array to tabulate a set of values

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

Results in

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

(First column is the (index))

+ +

Specifications

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

Compatibilidade de Navegadores

+ + + +

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

+ +

See also

+ + diff --git a/files/pt-pt/web/javascript/reference/global_objects/array/join/index.html b/files/pt-pt/web/javascript/reference/global_objects/array/join/index.html 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 +--- +
{{JSRef}}
+ +

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

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

Sintaxe

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

Parâmetros

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

Resultado

+ +

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

+ +

Descrição

+ +

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

+ +

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

+ +

Exemplos

+ +

Juntar um vetor de quatro formas diferentes

+ +

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

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

Juntar um objeto como vetor

+ +

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

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

Especificações

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

Compatibilidade

+ + + +

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

+ +

Veja também

+ + diff --git a/files/pt-pt/web/javascript/reference/global_objects/array/map/index.html b/files/pt-pt/web/javascript/reference/global_objects/array/map/index.html 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 +--- +
{{JSRef}}
+ +

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

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

Sintaxe

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

Parameteros

+ +
+
callback
+
+

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

+ +

A função callback aceita os seguintes argumentos:

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

Valor de retorno

+ +

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

+ +

Descrição

+ +

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

+ +

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

+ + + +

Quando não usar map()

+ +

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

+ +

Não deve usar map se:

+ + + +

Parameteros em detalhe

+ +

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

+ +

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

+ +

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

+ +

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

+ +

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

+ +

Polyfill

+ +

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

+ +

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

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

Examples

+ +

Mapping an array of numbers to an array of square roots

+ +

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

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

Using map to reformat objects in an array

+ +

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

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

Mapping an array of numbers using a function containing an argument

+ +

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

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

Using map generically

+ +

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

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

Using map generically querySelectorAll

+ +

This example shows how to iterate through a collection of objects collected by querySelectorAll. This is because querySelectorAll returns a NodeList (which is a collection of objects).

+ +

In this case, we return all the selected options' values on the screen:

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

An easier way would be the {{jsxref("Array.from()")}} method.

+ +

Tricky use case

+ +

(inspired by this blog post)

+ +

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

+ +

Consider:

+ +
["1", "2", "3"].map(parseInt)
+ +

While one might expect [1, 2, 3], the actual result is [1, NaN, NaN].

+ +

{{jsxref("parseInt")}} is often used with one argument, but takes two. The first is an expression and the second is the radix to the callback function, Array.prototype.map passes 3 arguments:

+ + + +

The third argument is ignored by {{jsxref("parseInt")}}—but not the second one! This is the source of possible confusion.

+ +

Here is a concise example of the iteration steps:

+ +
// parseInt(string, radix) -> map(parseInt(value, index))
+/*  first iteration  (index is 0): */ parseInt("1", 0)  // 1
+/*  second iteration (index is 1): */ parseInt("2", 1)  // NaN
+/*  third iteration  (index is 2): */ parseInt("3", 2)  // NaN
+
+ +

Then let's talk about solutions.

+ +
function returnInt(element) {
+  return parseInt(element, 10)
+}
+
+['1', '2', '3'].map(returnInt); // [1, 2, 3]
+// Actual result is an array of numbers (as expected)
+
+// Same as above, but using the concise arrow function syntax
+['1', '2', '3'].map( str => parseInt(str) )
+
+// A simpler way to achieve the above, while avoiding the "gotcha":
+['1', '2', '3'].map(Number)  // [1, 2, 3]
+
+// But unlike parseInt(), Number() will also return a float or (resolved) exponential notation:
+['1.1', '2.2e2', '3e300'].map(Number)  // [1.1, 220, 3e+300]
+
+// For comparison, if we use parseInt() on the array above:
+['1.1', '2.2e2', '3e300'].map( str => parseInt(str) ) // [1, 2, 3]
+
+ +

One alternative output of the map method being called with {{jsxref("parseInt")}} as a parameter runs as follows:

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

Mapped array contains undefined

+ +

When {{jsxref("undefined")}} or nothing is returned:

+ +
let numbers = [1, 2, 3, 4]
+let filteredNumbers = numbers.map(function(num, index) {
+  if (index < 3) {
+     return num
+  }
+})
+// index goes from 0, so the filterNumbers are 1,2,3 and undefined.
+// filteredNumbers is [1, 2, 3, undefined]
+// numbers is still [1, 2, 3, 4]
+
+
+ +

Especificações

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

Compatibilidade

+ +
+ + +

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

+
+ +

Ver também

+ + diff --git a/files/pt-pt/web/javascript/reference/global_objects/array/pop/index.html b/files/pt-pt/web/javascript/reference/global_objects/array/pop/index.html 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 +--- +
{{JSRef}}
+ +

O método pop() remove o último elemento de um array e retorna esse elemento. Este método altera o tamanho do array.

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

Syntax

+ +
arr.pop()
+ +

Valor retornado

+ +

O elemento removido do array; {{jsxref("undefined")}} se o array estiver vazio.

+ +

Descrição

+ +

O método pop remove o último elemento de um array e retorna esse elemento para a função que o chamou.

+ +

pop é um método intencionalmente genérico; este método pode ser {{jsxref("Function.call", "called", "", 1)}} ou {{jsxref("Function.apply", "applied", "", 1)}} para objectos parecidos com arrays. Objectos que não contenham a propriedade length (tamanho) que reflete o último elemento numa lista de consecutivas propriedades numéricas zero-based, pode não se comportar de maneira significativa.

+ +

Se o método pop() for chamado num array vazio este retorna {{jsxref("undefined")}}.

+ +

Exemplos

+ +

Remover o último elemento de um array

+ +

O seguinte exemplo cria um array peixes que contêm quatro elementos, e depois remove o último elemento.

+ +
var peixes = ['anjo', 'palhaço', 'mandarim', 'esturjão'];
+
+var popped = peixes.pop();
+
+console.log(peixes); // ['anjo', 'palhaço', 'mandarim']
+
+console.log(popped); // 'esturjão'
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Definição inicial. Implementada no JavaScript 1.2.
{{SpecName('ES5.1', '#sec-15.4.4.6', 'Array.prototype.pop')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-array.prototype.pop', 'Array.prototype.pop')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.prototype.pop', 'Array.prototype.pop')}}{{Spec2('ESDraft')}} 
+ +

Compatibilidade

+ +
+ + +

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

+
+ +

Ver também 

+ + diff --git a/files/pt-pt/web/javascript/reference/global_objects/array/reverse/index.html b/files/pt-pt/web/javascript/reference/global_objects/array/reverse/index.html 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 +--- +
{{JSRef}}
+ +

O método reverse() inverte um vector (Array). O primeiro elemento torna-se o último, e o último elemento torna-se o primeiro.

+ +
var a = ['um', 'dois', 'três'];
+a.reverse();
+
+console.log(a); // ['três', 'dois', 'um']
+
+ +

Sintaxe

+ +
a.reverse()
+ +

Valor devolvido

+ +

O vector (Array) invertido.

+ +

Descrição

+ +

O método reverse transpõe os elementos do vector que o chamou, mudando o vector, e devolvendo uma referência para o vector.

+ +

Exemplos

+ +

Invertendo os elementos num vector

+ +

O exemplo que se segue cria um vector a, que contém três elementos, e depois o inverte. A chamada a reverse() devolve uma referência para o vector invertido a.

+ +
var a = ['um', 'dois', 'três'];
+var invertido = a.reverse();
+
+console.log(a);        // ['três', 'dois', 'um']
+console.log(invertido); // ['três', 'dois', 'um']
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.4.4.8', 'Array.prototype.reverse')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-array.prototype.reverse', 'Array.prototype.reverse')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.prototype.reverse', 'Array.prototype.reverse')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

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

See also

+ + diff --git a/files/pt-pt/web/javascript/reference/global_objects/array/slice/index.html b/files/pt-pt/web/javascript/reference/global_objects/array/slice/index.html 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 +--- +
{{JSRef}}
+ +

O método slice() devolve uma cópia rasa (é feita uma cópia dos pointers se for um objeto) de uma parte de uma matriz num novo objeto de array selecionado do start (início incluído) ao end (fim excluído) onde o start e o end representam o índice de itens dessa matriz. A matriz original não é modificada.

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

Sintaxe

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

Parâmetros

+ +
+
start {{optional_inline}}
+
Indice de base zero, onde coméça a cópia.
+
Um índice negativo pode ser utilizado, indicando um intervalo a partir do fim da sequência. slice(-2) extrai os dois últimos elementos da sequência.
+
Se start é undefined, slice coméça a partir do indice 0.
+
Se start é maior que o último índice da sequência, uma matriz vazia é devolvida.
+
end {{optional_inline}}
+
Índice antes do qual se deve terminar a extração. slice extrai até o valor de indice end, mas sem incluir end. Por exemplo, slice(1,4) extrai do segundo até ao quarto elemento (elementos indexados 1, 2, e 3).
+
Pode ser utilizado um índice negativo, indicando o último índice a partir do fim da sequência. slice(2,-1) extrai do terceiro até ao penúltimo elemento na sequência.
+
Se end é omisso, slice extrai todos os elementos até ao fim da sequência (arr.length).
+
Se end é maior que o comprimento da sequência, slice extrai todos os elementos até ao fim da sequência (arr.length).
+
+ +

Resultado

+ +

Uma matriz nova contendo os elementos extraídos.

+ +

Descrição

+ +

slice não altera a matriz original. Devolve uma cópia rasa dos elementos da matriz original. Os elementos da matriz original são copiados para a matriz devolvida como se segue:

+ + + +

Se um novo elemento é adicionado a qualquer das matrizes, a outra matriz não é afetada.

+ +

Exemplos

+ +

Devolver uma porção duma matriz

+ +
let fruits = ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango']
+let citrus = fruits.slice(1, 3)
+
+// fruits contêm ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango']
+// citrus contêm ['Orange','Lemon']
+
+ +

Usar slice

+ +

No seguinte exemplo, slice cria uma array (matriz), newCar, a partir de myCar. Ambos incluem uma referência ao objeto myHonda. Quando a propriedade color (cor) de myHonda é mudada para purple (roxo), ambas matrizes refletem a alteração.

+ +
// Usando slice, cria newCar a partir de myCar.
+let myHonda = { color: 'red', wheels: 4, engine: { cylinders: 4, size: 2.2 } }
+let myCar = [myHonda, 2, 'cherry condition', 'purchased 1997']
+let newCar = myCar.slice(0, 2)
+
+// Imprime os valors de myCar, newCar, a propriadade
+// color de myHonda em ambas arrays.
+console.log('myCar = ' + JSON.stringify(myCar))
+console.log('newCar = ' + JSON.stringify(newCar))
+console.log('myCar[0].color = ' + myCar[0].color)
+console.log('newCar[0].color = ' + newCar[0].color)
+
+// Mude a propriadade color de myHonda.
+myHonda.color = 'purple'
+console.log('A nova cor de my Honda é ' + myHonda.color)
+
+// Imprime a propriadade color de myHonda em ambas arrays.
+console.log('myCar[0].color = ' + myCar[0].color)
+console.log('newCar[0].color = ' + newCar[0].color)
+
+ +

Este script imprime:

+ +
myCar = [{color: 'red', wheels: 4, engine: {cylinders: 4, size: 2.2}}, 2,
+         'cherry condition', 'purchased 1997']
+newCar = [{color: 'red', wheels: 4, engine: {cylinders: 4, size: 2.2}}, 2]
+myCar[0].color = red
+newCar[0].color = red
+A nova cor de my Honda é purple
+myCar[0].color = purple
+newCar[0].color = purple
+
+ +

Objetos parecidos com Array

+ +

O método slice tembém pode ser chamado para converter objetos / coleções do estilo matriz para um objeto Array. É só preciso {{jsxref("Function.prototype.bind", "bind")}} o método ao objeto. Os {{jsxref("Functions/arguments", "argumentos")}} dentro da função são um exemplo de um "objeto de estilo matriz".

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

Binding pode ser feito com o método {{jsxref("Function.prototype.call", "call()")}} de {{jsxref("Function.prototype")}} e também pode ser simplificado a usar  [].slice.call(arguments) invés de Array.prototype.slice.call.

+ +

Pode ser simplificado a usar {{jsxref("Function.prototype.bind", "bind")}}.

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

Especificações

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

Compatibilidade

+ + + +

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

+ +

Veja também

+ + diff --git a/files/pt-pt/web/javascript/reference/global_objects/arraybuffer/index.html b/files/pt-pt/web/javascript/reference/global_objects/arraybuffer/index.html 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 +--- +
{{JSRef}}
+ +
ArrayBuffer é um objeto utilizado para representar um buffer de dados em binário de tamanho pré-definido. Não é possivel manipular o conteudo do buffer diretamente; em vez disso, tem de se criar um dos typed array objects ou um objeto {{jsxref("DataView")}} que representa um buffer num formato especifico, e usa-o para ler e escrever  o conteudo do buffer. 
+ +
 
+ +

Sintaxe

+ +
new ArrayBuffer(length)
+
+ +

Parametros

+ +
+
length
+
O tamanho, em bytes, do array buffer que se pretende criar.
+
+ +

Retorno

+ +

 Um novo objecto do tipo ArrayBuffer do tamanho especificado. O respetivo conteudo é inicializado a 0.

+ +

Excepções

+ +

A {{jsxref("RangeError")}} é lançada caso o tamanho (length) é maior do que {{jsxref("Number.MAX_SAFE_INTEGER")}} (>= 2 ** 53) ou caso seja negativo.

+ +

Descrição

+ +

O construtor de ArrayBuffer cria um novo objeto do tipo ArrayBuffer com o tamanho especificado em bytes.

+ +

Obter um array buffer a partir de dados existentes

+ + + +

Propriedades

+ +
+
ArrayBuffer.length
+
Propriedade length do construtor de  ArrayBuffer cujo valor é 1.
+
{{jsxref("ArrayBuffer.@@species", "get ArrayBuffer[@@species]")}}
+
A função do contrutor que é usado para criar objetos derivados.
+
{{jsxref("ArrayBuffer.prototype")}}
+
Permite adicionar novas propriedades a todos os objetos do tipo ArrayBuffer.
+
+ +

Métodos

+ +
+
{{jsxref("ArrayBuffer.isView", "ArrayBuffer.isView(arg)")}}
+
Devolve true caso arg é  um tipo de representação do ArrayBuffer, como typed array objects ou {{jsxref("DataView")}}. Devolve false caso contrário
+
{{jsxref("ArrayBuffer.transfer", "ArrayBuffer.transfer(oldBuffer [, newByteLength])")}} {{experimental_inline}}
+
Devolve um novo objeto ArrayBuffer cujo conteúdo é obtido do oldBuffer e ou é truncado ou preenchido a zeros pelo  newByteLength.
+
+ +

Instâncias ArrayBuffer

+ +

Todas as instâncias de ArrayBuffer herdam de {{jsxref("ArrayBuffer.prototype")}}.

+ +

Propriedades

+ +

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

+ +

Métodos

+ +

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

+ +
+
{{jsxref("ArrayBuffer.slice()")}} {{non-standard_inline}}
+
Tem a mesma funcionalidade que {{jsxref("ArrayBuffer.prototype.slice()")}}.
+
+ +

Exemplo

+ +

Neste exemplo, criamos um buffer de 8 bytes com representação {{jsxref("Global_Objects/Int32Array", "Int32Array")}} a referênciar o buffer:

+ +
var buffer = new ArrayBuffer(8);
+var view   = new Int32Array(buffer);
+ +

Especificação

+ + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('Typed Array')}}{{Spec2('Typed Array')}}Substituido por ECMAScript 6.
{{SpecName('ES6', '#sec-arraybuffer-constructor', 'ArrayBuffer')}}{{Spec2('ES6')}} +

Definição inicial no stardard da ECMA. Especificar que new era necessário.

+
{{SpecName('ESDraft', '#sec-arraybuffer-constructor', 'ArrayBuffer')}}{{Spec2('ESDraft')}} 
+ +

Compatibilidade nos navegadores

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support7.0{{CompatGeckoDesktop("2")}}1011.65.1
ArrayBuffer() without new throws{{CompatUnknown}}{{CompatGeckoDesktop("44")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
ArrayBuffer.slice() {{non-standard_inline}}{{CompatNo}}{{CompatVersionUnknown}}
+ {{CompatNo}} {{CompatGeckoDesktop("53")}}
{{CompatNo}}{{CompatNo}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support4.0{{CompatVersionUnknown}}{{CompatGeckoMobile("2")}}1011.64.2
ArrayBuffer() without new throws{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("44")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
ArrayBuffer.slice() {{non-standard_inline}}{{CompatNo}}{{CompatNo}}{{CompatVersionUnknown}}
+ {{CompatNo}} {{CompatGeckoMobile("53")}}
{{CompatNo}}{{CompatNo}}{{CompatUnknown}}
+
+ +

Notas de compatibilidade

+ +

Com ECMAScript 2015, construtores de ArrayBuffer são obrigados a usar o operador {{jsxref("Operators/new", "new")}}. Daqui adiante ao invocar ArrayBuffer como uma função sem new irá lançar uma exceção {{jsxref("TypeError")}}.

+ +
var dv = ArrayBuffer(10);
+// TypeError: calling a builtin ArrayBuffer constructor
+// without new is forbidden
+ +
var dv = new ArrayBuffer(10);
+ +

Ver também

+ + diff --git a/files/pt-pt/web/javascript/reference/global_objects/asyncfunction/index.html b/files/pt-pt/web/javascript/reference/global_objects/asyncfunction/index.html 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 +--- +
{{JSRef}}
+ +
O constructor da função Async cria um novo objecto {{jsxref("Statements/async_function", "async function")}}. Em Javascript todas as funções asíncronas são na verdade objectos AsyncFunction.
+ +

 

+ +

Note-se que AsyncFunction não é um objecto global. Pode ser obtido da seguinte forma.

+ +
Object.getPrototypeOf(async function(){}).constructor
+
+ +

Síntaxe

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

Parâmetros

+ +
+
arg1, arg2, ... argN
+
Nomes usados pela função como nomes formais de argumentos . Cada um dos argumentos tem que ser uma string que corresponde a um identificador válido JavaScript ou uma lista separada por vírgulas; por exemplo "x", "theValue", ou "a,b".
+
functionBody
+
Uma string com os termos JavaScript que fazem parte da definição da função.
+
+ +

Descrição

+ +

Os objectos {{jsxref("Statements/async_function", "async function")}} criados com o constructor AsyncFunction passam por um parsing quando as funções são criadas. Isto é menos eficiente que declarar uma função asíncrona com {{jsxref("Statements/async_function", "async function expression")}} e chamá-la no código porque dessa forma a função passa pelo parsing ao mesmo tempo que o resto do código.

+ +

Todos os argumentos passados à função são tratados como os nomes dos identificadores dos parâmetros na função a ser criada, na ordem que são declarados.

+ +
+

Nota: {{jsxref("Statements/async_function", "async functions")}} criado com o constructor AsyncFunction não estão encapsulados ao contexto da sua criação, são sempre criados no âmbito global.

+ +

Ao correr, podem aceder às suas prórpias variáveis e às variáveis globais, no entanto não conseguem aceder às que estão no contexto donde o constructor AsyncFunction foi chamado. Isto é diferente de chamar {{jsxref("Global_Objects/eval", "eval")}} com código para uma função asíncrona.

+
+ +

A invocação do constructor AsyncFunction como uma função, i.e. sem usar o operador new tem o mesmo efeito que invocá-lo como constructor.

+ +

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

+ +

Propriedades

+ +
+
AsyncFunction.length
+
A propriedade comprimento do constructor do AsyncFunction, cujo valor é 1.
+
{{jsxref("AsyncFunction.prototype")}}
+
Permite adicionar propriedades a todos os objectos que são funções asíncronas.
+
+ +

AsyncFunction prototype object

+ +

Propriedades

+ +
{{page('/pt-PT/docs/Web/JavaScript/Reference/Global_Objects/AsyncFunction/prototype', 'Properties')}}
+ +

Instâncias de AsyncFunction

+ +

As instâncias de AsyncFunction herdam métodos e propriedades do {{jsxref("AsyncFunction.prototype")}}. Tal como com qualquer constructor pode-se mudar o prototype object para aplicar mudanças a todos as instâncias de AsyncFunction.

+ +

Exemplos

+ +

Exemplo de criação de uma função async a partir de um constructor AsyncFunction

+ +
function resolveAfter2Seconds(x) {
+  return new Promise(resolve => {
+    setTimeout(() => {
+      resolve(x);
+    }, 2000);
+  });
+}
+
+var AsyncFunction = Object.getPrototypeOf(async function(){}).constructor
+
+var a = new AsyncFunction('a',
+                          'b',
+                          'return await resolveAfter2Seconds(a) + await resolveAfter2Seconds(b);');
+
+a(10, 20).then(v => {
+  console.log(v); // prints 30 after 4 seconds
+});
+
+ +

Especificações

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-async-function-objects', 'AsyncFunction object')}}{{Spec2('ESDraft')}}Definição inicial em ES2017.
+ +

Compatibilidade de navegadores

+ +
+ + +

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

+
+ +

See also

+ + diff --git a/files/pt-pt/web/javascript/reference/global_objects/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 +--- +
{{JSRef}}
+ +

A propriedade AsyncFunction.prototype representa o objecto prototype {{jsxref("AsyncFunction")}}.

+ +

Description

+ +

Os objectos {{jsxref("AsyncFunction")}} são herdados de AsyncFunction.prototype e não podem ser modificados.

+ +

Propriedades

+ +
+
AsyncFunction.constructor
+
O valor inicial é {{jsxref("AsyncFunction")}}.
+
AsyncFunction.prototype[@@toStringTag]
+
Retorna "AsyncFunction".
+
+ +

Especificações

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-async-function-constructor-prototype', 'AsyncFunction.prototype')}}{{Spec2('ESDraft')}}Definição inicial ES2017.
+ +

Compatibilidade entre navegadores

+ +
+ + +

{{Compat("javascript.builtins.AsyncFunction.prototype")}}

+
+ +

Ver também

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

O objeto Boolean é um wrapper objeto para um valor booliano.

+ +

Sintaxe

+ +
new Boolean([value])
+ +

Parâmetros

+ +
+
value
+
Opcional. O valor incial do objeto Boolean.
+
+ +

Descrição

+ +

The value passed as the first parameter is converted to a boolean value, if necessary. If the value is omitted or is 0, -0, {{jsxref("null")}}, false, {{jsxref("NaN")}}, {{jsxref("undefined")}}, or the empty string (""), the object has an initial value of false. If the DOM object {{domxref("document.all")}} is passed as a parameter, the new boolean object also has an initial value of false. All other values, including any object or the string "false", create an object with an initial value of true.

+ +

Do not confuse the primitive Boolean values true and false with the true and false values of the Boolean object.

+ +

Any object of which the value is not {{jsxref("undefined")}} or {{jsxref("null")}}, including a Boolean object whose value is false, evaluates to true when passed to a conditional statement. For example, the condition in the following {{jsxref("Statements/if...else", "if")}} statement evaluates to true:

+ +
var x = new Boolean(false);
+if (x) {
+  // this code is executed
+}
+
+ +

This behavior does not apply to Boolean primitives. For example, the condition in the following {{jsxref("Statements/if...else", "if")}} statement evaluates to false:

+ +
var x = false;
+if (x) {
+  // this code is not executed
+}
+
+ +

Do not use a Boolean object to convert a non-boolean value to a boolean value. Instead, use Boolean as a function to perform this task:

+ +
var x = Boolean(expression);     // preferred
+var x = new Boolean(expression); // don't use
+
+ +

If you specify any object, including a Boolean object whose value is false, as the initial value of a Boolean object, the new Boolean object has a value of true.

+ +
var myFalse = Boolean(false);   // initial value of false
+var g = Boolean(myFalse);       // initial value of true
+var myString = new String('Hello'); // string object
+var s = Boolean(myString);      // initial value of true
+
+ +

Do not use a Boolean object in place of a Boolean primitive.

+ +

Propriedades

+ +
+
Boolean.length
+
Length property whose value is 1.
+
{{jsxref("Boolean.prototype")}}
+
Represents the prototype for the Boolean constructor.
+
+ +

Métodos

+ +

While the global Boolean object contains no methods of its own, it does inherit some methods through the prototype chain:

+ +

Instâncias Boolean

+ +

All Boolean instances inherit from {{jsxref("Boolean.prototype")}}. As with all constructors, the prototype object dictates instances' inherited properties and methods.

+ +

Propridades

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

Métodos

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

Exemplos

+ +

Criar objetos Boolean com um valor inicial de false

+ +
var bNoParam = Boolean();
+var bZero = Boolean(0);
+var bNull = Boolean(null);
+var bEmptyString = Boolean('');
+var bfalse = Boolean(false);
+
+ +

Criar objetos Boolean com um valor inicial de verdadeiro

+ +
var btrue = Boolean(true);
+var btrueString = Boolean('true');
+var bfalseString = Boolean('false');
+var bSuLin = Boolean('Su Lin');
+var bArrayProto = Boolean([]);
+var bObjProto = Boolean({});
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.6', 'Boolean')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-boolean-objects', 'Boolean')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-boolean-objects', 'Boolean')}}{{Spec2('ESDraft')}} 
+ +

Compatibilidade de navegador

+ +
+ + +

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

+
+ +

Consulte também

+ + diff --git a/files/pt-pt/web/javascript/reference/global_objects/encodeuri/index.html b/files/pt-pt/web/javascript/reference/global_objects/encodeuri/index.html 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 +--- +
{{jsSidebar("Objects")}}
+ +

O método encodeURI() codifica um Uniform Resource Identifier (URI) substituindo cada instancia de determinados caracteres por um, dois, três, ou quatro sequências de escape que representem a codificação UTF-8 do caracter (apenas serão quatro sequências de caracteres de escape para caracteres compostos por dois caracteres de "substituição").

+ +

Sintaxe

+ +
encodeURI(URI)
+ +

Parâmetros

+ +
+
URI
+
Um Uniform Resource Identifier completo.
+
+ +

Descrição

+ +

Assumindo que o URI é um URI completo, não serão codificados caracteres reservados que tenham significado especial no URI.

+ +

encodeURI substitui todos os caracteres excepto as seguintes sequências de escape UTF-8:

+ + + + + + + + + + + + + + + + + + + + +
TipoIncluído
Caracteres reservados; , / ? : @ & = + $
Caracteres excluídosalfabéticos, dígitos decimais , - _ . ! ~ * ' ( )
Ponto#
+ +

Note-se que o método encodeURI não consegue criar correctamente os pedidos HTTP GET e POST, o mesmo aplica-se para XMLHTTPRequests, porque os caracteres "&", "+", e "=" não são codificados, por se tratarem de caracteres especiais nos pedidos GET e POST. {{jsxref("encodeURIComponent")}}, no entanto, codifica estes caracteres.

+ +

Note-se que será lançado um {{jsxref("URIError")}} caso se tente codificar um substituto que não faça parte de um par superior-inferior, p.ex.,

+ +
// par superior-inferior ok
+console.log(encodeURI('\uD800\uDFFF'));
+
+// substituição única de par superior lança "URIError: malformed URI sequence"
+console.log(encodeURI('\uD800'));
+
+// substituição única de par inferior lança "URIError: malformed URI sequence"
+console.log(encodeURI('\uDFFF')); 
+ +

Note-se também que caso se pretenda seguir a mais recente norma para URLs RFC3986, que torna os parênteses rectos reservados (para IPv6) e, por consequência, não será codificado quando fizer parte de um URL (como um host), o seguinte exemplo de código pode ajudar:

+ +
function fixedEncodeURI (str) {
+    return encodeURI(str).replace(/%5B/g, '[').replace(/%5D/g, ']');
+}
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition.
{{SpecName('ES5.1', '#sec-15.1.3.3', 'encodeURI')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-encodeuri-uri', 'encodeURI')}}{{Spec2('ES6')}} 
+ +

Compatibilidade com navegador

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FuncionalidadeChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FuncionalidadeAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Veja também

+ + diff --git a/files/pt-pt/web/javascript/reference/global_objects/function/arguments/index.html b/files/pt-pt/web/javascript/reference/global_objects/function/arguments/index.html 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 +--- +
{{JSRef}} {{deprecated_header}}
+ +
A propriedade function.arguments refere-se a um objecto com aspecto de array que corresponde aos argumentos da função. Ao invés disso, use a variável {{jsxref("Functions/arguments", "arguments")}}. Esta propriedade é proibida no modo strict devido ao tail call optimization.
+ +

Descrição

+ +

A síntaxe function.arguments está obsoleta. A forma recomendade de aceder ao objecto {{jsxref("Functions/arguments", "arguments")}} disponível nas função é usar simplesment a variável {{jsxref("Functions/arguments", "arguments")}}.

+ +

No caso de recursão isto é, se uma funão f aparece várias vezes na stack, o valor de f.arguments representa os argumentos correspondentes à mais recente chamada da função.

+ +

O valor da propriedade arguments é tipicamente null se não há nenuma invocação da função a acontecer, ou seja, a função foi chamada mas ainda não retornou.

+ +

Exemplos

+ +
function f(n) { g(n - 1); }
+
+function g(n) {
+  console.log('antes: ' + g.arguments[0]);
+  if (n > 0) { f(n); }
+  console.log('depois: ' + g.arguments[0]);
+}
+
+f(2);
+
+console.log('retornado: ' + g.arguments);
+
+// Output
+
+// antes: 1
+// antes: 0
+// depois: 0
+// depois: 1
+// retornado: null
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}} +

Definição inicial. Implementado em JavaScript 1.0. Tornado obsoleto a favor de {{jsxref("Functions/arguments", "arguments")}} em ES3.

+
{{SpecName('ES5.1', '#sec-10.6', 'arguments object')}}{{Spec2('ES5.1')}}Objecto {{jsxref("Functions/arguments", "arguments")}}
{{SpecName('ES6', '#sec-arguments-object', 'arguments object')}}{{Spec2('ES6')}}Objecto {{jsxref("Functions/arguments", "arguments")}}
{{SpecName('ESDraft', '#sec-arguments-object', 'arguments object')}}{{Spec2('ESDraft')}}Objecto {{jsxref("Functions/arguments", "arguments")}}
+ +

Compatibilidade navegadores

+ +
+ + +

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

+
+ +

Ver também

+ + diff --git a/files/pt-pt/web/javascript/reference/global_objects/function/call/index.html b/files/pt-pt/web/javascript/reference/global_objects/function/call/index.html 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 +--- +
{{JSRef}}
+ +

O método call() realiza a chamada de uma função com o parâmetros this além de outros parâmetros fornecidos individualmente.

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

Sintaxe

+ +
func.call([thisArg[, arg1, arg2, ...argN]])
+ +

Parâmetros

+ +
+
thisArg {{optional_inline}}
+
O valor de this fornecido ao chamar func.
+
+ +
+

Aviso: Em certos casos, thisArg pode não ser o valor que o método vê.

+ +

Se o método for uma função em {{jsxref("Strict_mode", "non-strict mode", "", 1)}}, {{jsxref("Global_Objects/null", "null")}} e {{jsxref("Global_Objects/undefined", "undefined")}} são substituídos pelo objeto global, e valores primitivos são convertidos em objetos.

+
+ +
+
arg1, arg2, ...argN {{optional_inline}}
+
Parâmetros para a função.
+
+ +

Resultado

+ +

O resultado ao chamar a função em questão com os parâmetros this e os outros argumentos especificados.

+ +

Descrição

+ +

call() permite uma função / método pertencendo a um objeto, ser atribuída a outro objeto e ser chamada desse mesmo.

+ +

call() fornece um novo valor para this à função / método. Com call(), pode escrever um método uma vez, e depois herdar o método noutro objeto, sem ter de rescrever a função para o novo objeto.

+ +
+

Nota: Apesar de a sintaxe da função ser quase idêntica à da {{jsxref("Function.prototype.apply", "apply()")}}, a principal diferença é que call() aceita uma lista de argumentos (arg1, arg2, ...argN), enquanto apply() aceita uma matriz de argumentos ([arg1, arg2, ...argN]).

+
+ +

Exemplos

+ +

Usar call para encadear construtores dum objeto

+ +

É possível utilizar call para encadear construtores para um objeto (como em Java).

+ +

No exemplo abaixo, o construtor para o objeto Product é definido com dois parâmetros: name e price.

+ +

Duas outras funções, Food e Toy, invocam Product passando os parâmetros thisname e price. As funções Food e Toy também definem a propriadade category.

+ +
function Product(name, price) {
+  this.name = name;
+  this.price = price;
+}
+
+function Food(name, price) {
+  Product.call(this, name, price);
+  this.category = 'food';
+}
+
+function Toy(name, price) {
+  Product.call(this, name, price);
+  this.category = 'toy';
+}
+
+const cheese = new Food('feta', 5);
+const fun = new Toy('robot', 40);
+ +

Usar call para invocar uma função anónima

+ +

Neste exemplo, criamos uma função anónima e utilizamos call para invocá-la em cada objeto na matriz.

+ +

O principal objetivo da função anónima é inserir a função print em cada objeto. A função print imprimir o índice do objeto na matriz em que se encontra.

+ +
+

Passar o objeto desta forma (como this) não é necessário, mas foi feito de forma a exemplificar a função.

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

Usar call para invocar a função sem especificar o primeiro argumento

+ +

No exemplo abaixo, quando chamamos a função display sem passar o primeiro argumento. Se o primeiro argumento não é especificado, o objeto global é atribuído a this.
+  

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

Aviso: Em "strict mode", o valor de this é undefined, exemplificado em baixo.

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

Especificações

+ + + + + + + + + + + + +
Especificação
{{SpecName('ESDraft', '#sec-function.prototype.call', 'Function.prototype.call')}}
+ +

Browser compatibility

+ + + +

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

+ +

Veja também

+ + diff --git a/files/pt-pt/web/javascript/reference/global_objects/function/index.html b/files/pt-pt/web/javascript/reference/global_objects/function/index.html 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 +--- +
{{JSRef}}
+ +

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

+ +

Syntax

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

Parameters

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

Description

+ +

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

+ +

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

+ +

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

+ +

Properties and Methods of Function

+ +

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

+ +

Function prototype object

+ +

Properties

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

Methods

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

Function instances

+ +

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

+ +

Examples

+ +

Specifying arguments with the Function constructor

+ +

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

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

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

+ +

Difference between Function constructor and function declaration

+ +

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

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

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.3', 'Function')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-function-objects', 'Function')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-function-objects', 'Function')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

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

See also

+ + diff --git a/files/pt-pt/web/javascript/reference/global_objects/index.html b/files/pt-pt/web/javascript/reference/global_objects/index.html 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 +--- +
{{jsSidebar("Objects")}}
+ +

Resumo

+ +

Este capítulo documenta todos os objectos built-in do JavaScript standard, juntamente com os seus métodos e propriedades.

+ +
+

O termo "objectos globais" (ou objectos built-in standard) não é para ser confundido com objecto global. Aqui, os objectos globais referem-se a objectos no scope global (mas apenas se o modo strict do ECMAScript 5 não estiver a ser usado! Senão retorna undefined). O próprio global object pode ser acedido através do operador {{jsxref("Operators/this", "this")}} no scope global. Na verdade, o scope global consiste nas propriedades do objecto global (incluíndo propriedades herdadas, se alguma).

+ +

Outros objectos no scope global são criados através do script do utilizador or fornecidos pela aplicação host. Os objectos do host disponíveis no contexto browser são documentados na referência da API. Para mais informações sobre a distinção entre DOM e o núcleo do JavaScript, ver exposição das tecnologias do JavaScript.

+ +

Objetos padrão (por categoria)

+ +

Propriedades do valor

+ +

Estas propriedades globais devolvem um valor simples; estas não têm propriedades ou métodos.

+ + + +

Propriedades da função

+ +

Estas funções globais - funções que são chamadas no mundo ao invés de um objeto - devolvem diretamente os seus resultados para o chamador.

+ + + +

Objetos fundamentais

+ +

Estes são os objetos básicos, fundamentais, em que todos os outros objetos são baseados. Isto inclui objetos que representam objetos gerais, funções, e erros.

+ + + +

Números e datas

+ +

Objectos que lidam com números, datas e cálculos matemáticos.

+ + + +

Processamento de texto

+ +

Objectos para manipular texto.

+ + + +

Coleções indexadas

+ +

Coleções ordenadas por um indíce. Objectos do tipo array.

+ + + +

Coleções por chave

+ +

Coleções de objectos como chaves. Elementos iteráveis por ordem de inserção.

+ + + +

Dados estruturados

+ +

Buffers de dados e JavaScript Object Notation (JSON).

+ + + +

Objectos de abstração de controlo

+ + + +

Reflexão

+ + + +

Internacionalização

+ +

Adições ao núcleo do ECMAScript para funcionalidades de linguagens sensíveis.

+ + + +

Objetos não padrão

+ + + +

Outros

+ + +
+ +

 

diff --git a/files/pt-pt/web/javascript/reference/global_objects/infinity/index.html b/files/pt-pt/web/javascript/reference/global_objects/infinity/index.html 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 +--- +
{{jsSidebar("Objects")}}
+ +

A propriedade global Infinity é um valor numérico que representa o infinito.

+ +

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

+ +
{{EmbedInteractiveExample("pages/js/globalprops-infinity.html")}}
+ + + +

Descrição

+ +

Infinity é uma propriedade do objeto global. Isto é para dizer que é um variável com um escopo global.

+ +

O valor inicial do Infinity é {{jsxref("Number.POSITIVE_INFINITY")}}. O valor Infinity (infinito positivo) é maior que qualquer outro número.

+ +

Este valor age de form diferente do infinito matematico; veja {{jsxref("Number.POSITIVE_INFINITY")}} para mais detalhes.

+ +

Como definido na especificação ECMAScript 5, Infinity é read-only (implementado em JavaScript 1.8.5 / Firefox 4).

+ +

Exemplos

+ +

Usar Infinity

+ +
console.log(Infinity          ); /* Infinity */
+console.log(Infinity + 1      ); /* Infinity */
+console.log(Math.pow(10, 1000)); /* Infinity */
+console.log(Math.log(0)       ); /* -Infinity */
+console.log(1 / Infinity      ); /* 0 */
+console.log(1 / 0             ); /* Infinity */
+
+ +

Especificações

+ + + + + + + + + + + + +
Especificação
{{SpecName('ESDraft', '#sec-value-properties-of-the-global-object-infinity', 'Infinity')}}
+ +

Compatibilidade

+ + + +

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

+ +

Veja também

+ + diff --git a/files/pt-pt/web/javascript/reference/global_objects/math/ceil/index.html b/files/pt-pt/web/javascript/reference/global_objects/math/ceil/index.html 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 +--- +
{{JSRef}}
+ +

A função Math.ceil() retorna um inteiro smallest (sem casas decimais) maior ou igual ao n.º passado como parâmetro. Por exemplo ao fazer Math.ceil(3.01) o valor retornado é 4, ao fazer Math.ceil(-5.01) o retorno é -5, ao fazer Math.ceil(7) o valor devolvido é 7. 

+ +

Sintaxe

+ +
Math.ceil(x)
+ +

Parametros

+ +
+
x
+
Um número.
+
+ +

Valor de retorno

+ +

Um inteiro smallest maior ou igual ao n.º passado como parâmetro.

+ +

Descrição

+ +

Como ceil() é um método estático de  Math,  pode sempre ser usado como Math.ceil(), o objeto Math não é um construtor. 

+ +

Exemplos

+ +

Utilizando Math.ceil()

+ +

Seguem exemplos da utilização de Math.ceil().

+ +
Math.ceil(.95);    // 1
+Math.ceil(4);      // 4
+Math.ceil(7.004);  // 8
+Math.ceil(-0.95);  // -0
+Math.ceil(-4);     // -4
+Math.ceil(-7.004); // -7
+
+ +

Ajustamento decimal 

+ +
// Closure
+(function() {
+  /**
+   * Decimal adjustment of a number.
+   *
+   * @param {String}  type  The type of adjustment.
+   * @param {Number}  value The number.
+   * @param {Integer} exp   The exponent (the 10 logarithm of the adjustment base).
+   * @returns {Number} The adjusted value.
+   */
+  function decimalAdjust(type, value, exp) {
+    // If the exp is undefined or zero...
+    if (typeof exp === 'undefined' || +exp === 0) {
+      return Math[type](value);
+    }
+    value = +value;
+    exp = +exp;
+    // If the value is not a number or the exp is not an integer...
+    if (isNaN(value) || !(typeof exp === 'number' && exp % 1 === 0)) {
+      return NaN;
+    }
+    // Shift
+    value = value.toString().split('e');
+    value = Math[type](+(value[0] + 'e' + (value[1] ? (+value[1] - exp) : -exp)));
+    // Shift back
+    value = value.toString().split('e');
+    return +(value[0] + 'e' + (value[1] ? (+value[1] + exp) : exp));
+  }
+
+  // Decimal round
+  if (!Math.round10) {
+    Math.round10 = function(value, exp) {
+      return decimalAdjust('round', value, exp);
+    };
+  }
+  // Decimal floor
+  if (!Math.floor10) {
+    Math.floor10 = function(value, exp) {
+      return decimalAdjust('floor', value, exp);
+    };
+  }
+  // Decimal ceil
+  if (!Math.ceil10) {
+    Math.ceil10 = function(value, exp) {
+      return decimalAdjust('ceil', value, exp);
+    };
+  }
+})();
+
+// Round
+Math.round10(55.55, -1);   // 55.6
+Math.round10(55.549, -1);  // 55.5
+Math.round10(55, 1);       // 60
+Math.round10(54.9, 1);     // 50
+Math.round10(-55.55, -1);  // -55.5
+Math.round10(-55.551, -1); // -55.6
+Math.round10(-55, 1);      // -50
+Math.round10(-55.1, 1);    // -60
+// Floor
+Math.floor10(55.59, -1);   // 55.5
+Math.floor10(59, 1);       // 50
+Math.floor10(-55.51, -1);  // -55.6
+Math.floor10(-51, 1);      // -60
+// Ceil
+Math.ceil10(55.51, -1);    // 55.6
+Math.ceil10(51, 1);        // 60
+Math.ceil10(-55.59, -1);   // -55.5
+Math.ceil10(-59, 1);       // -50
+
+ +

Especificações 

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationEstadoComentário
{{SpecName('ES1')}}{{Spec2('ES1')}}Definição inicial JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.8.2.6', 'Math.ceil')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-math.ceil', 'Math.ceil')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-math.ceil', 'Math.ceil')}}{{Spec2('ESDraft')}}
+ +

Browser compatibility

+ + + +

{{Compat("javascript.builtins.Math.ceil")}}

+ +

See also

+ + diff --git a/files/pt-pt/web/javascript/reference/global_objects/math/index.html b/files/pt-pt/web/javascript/reference/global_objects/math/index.html 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 +--- +
{{JSRef}}
+ +

Math é um objecto integrado que tem propriedades e métodos correspondentes a constantes e funções matemáticas. Não é um objecto função.

+ +

Descrição

+ +

Contrariamente aos outros objectos globais, Math não é um construtor. Todas as propriedades e métodos de Math são estáticas. Refere-se a constante pi com Math.PI e chama-se a função de seno com Math.sin(x), em que x é o argumento do método. As constantes estão definidas com a precisão completa dos números reais do JavaScript.

+ +

Para extender o objecto Math, não se usa o protótipo. Em vez disso extende-se directamente o objecto Math:

+ +

Math.nomeProp=valorProp;

+ +

Math.nomeMetodo=refMetodo;

+ +

Propriedades

+ +
+
{{jsxref("Math.E")}}
+
Euler's constant and the base of natural logarithms, approximately 2.718.
+
{{jsxref("Math.LN2")}}
+
Natural logarithm of 2, approximately 0.693.
+
{{jsxref("Math.LN10")}}
+
Natural logarithm of 10, approximately 2.303.
+
{{jsxref("Math.LOG2E")}}
+
Base 2 logarithm of E, approximately 1.443.
+
{{jsxref("Math.LOG10E")}}
+
Base 10 logarithm of E, approximately 0.434.
+
{{jsxref("Math.PI")}}
+
Ratio of the circumference of a circle to its diameter, approximately 3.14159.
+
{{jsxref("Math.SQRT1_2")}}
+
Square root of 1/2; equivalently, 1 over the square root of 2, approximately 0.707.
+
{{jsxref("Math.SQRT2")}}
+
Square root of 2, approximately 1.414.
+
+ +

Métodos

+ +
+

Note that the trigonometric functions (sin(), cos(), tan(), asin(), acos(), atan(), atan2()) expect or return angles in radians. To convert radians to degrees, divide by (Math.PI / 180), and multiply by this to convert the other way.

+
+ +
+

Note that many math functions have a precision that's implementation-dependent. This means that different browsers can give a different result, and even the same JS engine on a different OS or architecture can give different results.

+
+ +
+
{{jsxref("Global_Objects/Math/abs", "Math.abs(x)")}}
+
Returns the absolute value of a number.
+
{{jsxref("Global_Objects/Math/acos", "Math.acos(x)")}}
+
Returns the arccosine of a number.
+
{{jsxref("Global_Objects/Math/acosh", "Math.acosh(x)")}}
+
Returns the hyperbolic arccosine of a number.
+
{{jsxref("Global_Objects/Math/asin", "Math.asin(x)")}}
+
Returns the arcsine of a number.
+
{{jsxref("Global_Objects/Math/asinh", "Math.asinh(x)")}}
+
Returns the hyperbolic arcsine of a number.
+
{{jsxref("Global_Objects/Math/atan", "Math.atan(x)")}}
+
Returns the arctangent of a number.
+
{{jsxref("Global_Objects/Math/atanh", "Math.atanh(x)")}}
+
Returns the hyperbolic arctangent of a number.
+
{{jsxref("Global_Objects/Math/atan2", "Math.atan2(y, x)")}}
+
Returns the arctangent of the quotient of its arguments.
+
{{jsxref("Global_Objects/Math/cbrt", "Math.cbrt(x)")}}
+
Returns the cube root of a number.
+
{{jsxref("Global_Objects/Math/ceil", "Math.ceil(x)")}}
+
Returns the smallest integer greater than or equal to a number.
+
{{jsxref("Global_Objects/Math/clz32", "Math.clz32(x)")}}
+
Returns the number of leading zeroes of a 32-bit integer.
+
{{jsxref("Global_Objects/Math/cos", "Math.cos(x)")}}
+
Returns the cosine of a number.
+
{{jsxref("Global_Objects/Math/cosh", "Math.cosh(x)")}}
+
Returns the hyperbolic cosine of a number.
+
{{jsxref("Global_Objects/Math/exp", "Math.exp(x)")}}
+
Returns Ex, where x is the argument, and E is Euler's constant (2.718…), the base of the natural logarithm.
+
{{jsxref("Global_Objects/Math/expm1", "Math.expm1(x)")}}
+
Returns subtracting 1 from exp(x).
+
{{jsxref("Global_Objects/Math/floor", "Math.floor(x)")}}
+
Returns the largest integer less than or equal to a number.
+
{{jsxref("Global_Objects/Math/fround", "Math.fround(x)")}}
+
Returns the nearest single precision float representation of a number.
+
{{jsxref("Global_Objects/Math/hypot", "Math.hypot([x[, y[, …]]])")}}
+
Returns the square root of the sum of squares of its arguments.
+
{{jsxref("Global_Objects/Math/imul", "Math.imul(x, y)")}}
+
Returns the result of a 32-bit integer multiplication.
+
{{jsxref("Global_Objects/Math/log", "Math.log(x)")}}
+
Returns the natural logarithm (loge, also ln) of a number.
+
{{jsxref("Global_Objects/Math/log1p", "Math.log1p(x)")}}
+
Returns the natural logarithm (loge, also ln) of 1 + x for a number x.
+
{{jsxref("Global_Objects/Math/log10", "Math.log10(x)")}}
+
Returns the base 10 logarithm of a number.
+
{{jsxref("Global_Objects/Math/log2", "Math.log2(x)")}}
+
Returns the base 2 logarithm of a number.
+
{{jsxref("Global_Objects/Math/max", "Math.max([x[, y[, …]]])")}}
+
Returns the largest of zero or more numbers.
+
{{jsxref("Global_Objects/Math/min", "Math.min([x[, y[, …]]])")}}
+
Returns the smallest of zero or more numbers.
+
{{jsxref("Global_Objects/Math/pow", "Math.pow(x, y)")}}
+
Returns base to the exponent power, that is, baseexponent.
+
{{jsxref("Global_Objects/Math/random", "Math.random()")}}
+
Returns a pseudo-random number between 0 and 1.
+
{{jsxref("Global_Objects/Math/round", "Math.round(x)")}}
+
Returns the value of a number rounded to the nearest integer.
+
{{jsxref("Global_Objects/Math/sign", "Math.sign(x)")}}
+
Returns the sign of the x, indicating whether x is positive, negative or zero.
+
{{jsxref("Global_Objects/Math/sin", "Math.sin(x)")}}
+
Returns the sine of a number.
+
{{jsxref("Global_Objects/Math/sinh", "Math.sinh(x)")}}
+
Returns the hyperbolic sine of a number.
+
{{jsxref("Global_Objects/Math/sqrt", "Math.sqrt(x)")}}
+
Returns the positive square root of a number.
+
{{jsxref("Global_Objects/Math/tan", "Math.tan(x)")}}
+
Returns the tangent of a number.
+
{{jsxref("Global_Objects/Math/tanh", "Math.tanh(x)")}}
+
Returns the hyperbolic tangent of a number.
+
Math.toSource() {{non-standard_inline}}
+
Returns the string "Math".
+
{{jsxref("Global_Objects/Math/trunc", "Math.trunc(x)")}}
+
Returns the integral part of the number x, removing any fractional digits.
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.8', 'Math')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math-object', 'Math')}}{{Spec2('ES6')}}New methods {{jsxref("Math.log10()", "log10()")}}, {{jsxref("Math.log2()", "log2()")}}, {{jsxref("Math.log1p()", "log1p()")}}, {{jsxref("Math.expm1()", "expm1()")}}, {{jsxref("Math.cosh()", "cosh()")}}, {{jsxref("Math.sinh()", "sinh()")}}, {{jsxref("Math.tanh()", "tanh()")}}, {{jsxref("Math.acosh()", "acosh()")}}, {{jsxref("Math.asinh()", "asinh()")}}, {{jsxref("Math.atanh()", "atanh()")}}, {{jsxref("Math.hypot()", "hypot()")}}, {{jsxref("Math.trunc()", "trunc()")}}, {{jsxref("Math.sign()", "sign()")}}, {{jsxref("Math.imul()", "imul()")}}, {{jsxref("Math.fround()", "fround()")}}, {{jsxref("Math.cbrt()", "cbrt()")}} and {{jsxref("Math.clz32()", "clz32()")}} added.
{{SpecName('ESDraft', '#sec-math-object', 'Math')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

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

See also

+ + diff --git a/files/pt-pt/web/javascript/reference/global_objects/number/index.html b/files/pt-pt/web/javascript/reference/global_objects/number/index.html 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 +--- +
{{JSRef}}
+ +

O objecto JavaScript Number é um objecto abstraído que te permite trabalhar com valores numéricos. Um objecto Number é criado usando o constructor Number().

+ +

Constructor

+ +
new Number(valor);
+ +

Parâmetro

+ +
+
valor
+
O valor numérico representado pelo objecto que está a ser criado.
+
+ +

Descrição

+ +

Os usos mais comuns para o objecto Number são:

+ + + +

Propriedades

+ +
+
{{jsxref("Number.EPSILON")}} {{experimental_inline}}
+
O intervalo mais pequeno entre dois números representáveis.
+
{{jsxref("Number.MAX_SAFE_INTEGER")}} {{experimental_inline}}
+
O maior inteiro bem representado em JavaScript (253 - 1).
+
{{jsxref("Number.MAX_VALUE")}}
+
O maior número positivo representável.
+
{{jsxref("Number.MIN_SAFE_INTEGER")}} {{experimental_inline}}
+
O menor inteiro bem representado em JavaScript (-(253 - 1)).
+
{{jsxref("Number.MIN_VALUE")}}
+
O menor número positivo representável - ou seja, o número positivo mais próximo de zero (sem ser o zero).
+
{{jsxref("Number.NaN")}}
+
Valor especial para representar um "não número".
+
{{jsxref("Number.NEGATIVE_INFINITY")}}
+
Valor especial para representar o infinito negativo; retornado em caso de overflow.
+
{{jsxref("Number.POSITIVE_INFINITY")}}
+
Valor especial para representar o infinito; retornado em caso de overflow.
+
{{jsxref("Number.prototype")}}
+
Permite adicionar propriedades ao objecto Number.
+
+ +

Métodos

+ +
+
{{jsxref("Number.isNaN()")}} {{experimental_inline}}
+
Determina se o valor passado é NaN.
+
{{jsxref("Number.isFinite()")}} {{experimental_inline}}
+
Determina se o valor passado é um número finito.
+
{{jsxref("Number.isInteger()")}} {{experimental_inline}}
+
Determina se o número passado é um inteiro.
+
{{jsxref("Number.isSafeInteger()")}} {{experimental_inline}}
+
Determina se o valor passado é um inteiro bem representado (número entre -(253 - 1) e 253 - 1).
+
{{jsxref("Number.toInteger()")}} {{obsolete_inline}}
+
Usado para avaliar o valor passado e convertê-lo num inteiro (ou {{jsxref("Global_Objects/Infinity", "Infinity")}}), mas foi removido.
+
{{jsxref("Number.parseFloat()")}} {{experimental_inline}}
+
O valor é o mesmo que {{jsxref("Global_Objects/parseFloat", "parseFloat()")}} de um objecto global.
+
{{jsxref("Number.parseInt()")}} {{experimental_inline}}
+
O valor é o mesmo que {{jsxref("Global_Objects/parseInt", "parseInt()")}} de um objecto global.
+
+ +

Instâncias de Number

+ +

Todas as instâncias de Number herdam de {{jsxref("Number.prototype")}}. O objecto protótipo (prototype) do constructor de Number pode ser modificado para afectar todas as instâncias de Number.

+ +

Métodos

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

Exemplos

+ +

Usar  o objecto Number para atribuír valores a variáveis numéricas

+ +

O seguinte exemplo usa as propriedades do objecto Number para atribuír valores a várias variáveis numéricas: 

+ +
var biggestNum = Number.MAX_VALUE;
+var smallestNum = Number.MIN_VALUE;
+var infiniteNum = Number.POSITIVE_INFINITY;
+var negInfiniteNum = Number.NEGATIVE_INFINITY;
+var notANum = Number.NaN;
+
+ +

Limite inteiro para Number

+ +

O seguinte exemplo mostra o mínimo e máximo valores inteiros que podem ser representados como um objecto Number (para mais detalhes, consulta o standard do ECMAScript, capítulo 8.5 The Number Type):

+ +
var biggestInt = 9007199254740992;
+var smallestInt = -9007199254740992;
+
+ +

Ao analisar dados que foram serializados para JSON, os valores inteiros fora deste limite são expectáveis de ficar corrompidos quando o analisador de JSON os tentar converter para o tipo Number. Como possível alternativa, usa {{jsxref("String")}}.

+ +

Usar Number para converter um objecto Date

+ +

O seguinte exemplo converte o objecto {{jsxref("Date")}} num valor numérico usando Number como função:

+ +
var d = new Date('December 17, 1995 03:24:00');
+console.log(Number(d));
+
+ +

Este código imprime "819199440000".

+ +

Converter strings numéricas para números

+ +
Number("123")     // 123
+Number("")        // 0
+Number("0x11")    // 17
+Number("0b11")    // 3
+Number("0o11")    // 9
+Number("foo")     // NaN
+Number("100a")    // NaN
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('ES1')}}{{Spec2('ES1')}}Definição inicial. Implementado em JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.7', 'Number')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-number-objects', 'Number')}}{{Spec2('ES6')}}Adicionados novas propriedades e métodos: ({{jsxref("Number.EPSILON", "EPSILON")}}, {{jsxref("Number.isFinite", "isFinite")}}, {{jsxref("Number.isInteger", "isInteger")}}, {{jsxref("Number.isNaN", "isNaN")}}, {{jsxref("Number.parseFloat", "parseFloat")}}, {{jsxref("Number.parseInt", "parseInt")}})
+ +

Compatibilidade dos browsers

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FuncionalidadeChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FuncionalidadeAndroidChrome para AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Ver também

+ + diff --git a/files/pt-pt/web/javascript/reference/global_objects/number/isfinite/index.html b/files/pt-pt/web/javascript/reference/global_objects/number/isfinite/index.html 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 +--- +
{{JSRef}}
+ +

O método Number.isFinite() determina se o valor passado é um número finito.

+ +

Sintaxe

+ +
Number.isFinite(valor)
+ +

Parâmetros

+ +
+
valor
+
O valor a ser testado.
+
+ +

Descrição

+ +

Em comparação com a função global {{jsxref("Global_Objects/isFinite", "isFinite()")}}, Number.isFinite() não converte forçosamente o parâmetro num number. Isto significa que apenas para valores do tipo number, finitos, retorna true.

+ +

Exemplos

+ +
Number.isFinite(Infinity);  // false
+Number.isFinite(NaN);       // false
+Number.isFinite(-Infinity); // false
+
+Number.isFinite(0);         // true
+Number.isFinite(2e64);      // true
+
+Number.isFinite('0');       // false, teria sido true com a função
+                            // global isFinite('0')
+
+ +

Polyfill

+ +
Number.isFinite = Number.isFinite || function(value) {
+    return typeof value === "number" && isFinite(value);
+}
+
+ +

Especificações

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES6', '#sec-number.isfinite', 'Number.isInteger')}}{{Spec2('ES6')}}Initial definition.
+ +

Compatibilidade dos browsers

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FuncionalidadeChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{CompatChrome("19")}}{{CompatGeckoDesktop("16")}}{{CompatNo}}{{CompatOpera("15")}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FuncionalidadeAndroidChrome para AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("16")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

Ver também

+ + diff --git a/files/pt-pt/web/javascript/reference/global_objects/number/isinteger/index.html b/files/pt-pt/web/javascript/reference/global_objects/number/isinteger/index.html 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 +--- +
{{JSRef}}
+ +

O método Number.isInteger() determina se o valor passado é um inteiro.

+ +

Sintaxe

+ +
Number.isInteger(valor)
+ +

Parâmteros

+ +
+
valor
+
O valor a ser testado por ser um inteiro.
+
+ +

Descrição

+ +

Se o valor a ser testado for um inteiro, retorna true, senão retorna false. Se o valor for {{jsxref("Global_Objects/NaN", "NaN")}} ou infinito, retorna false.

+ +

Exemplos

+ +
Number.isInteger(0.1);     // false
+Number.isInteger(1);       // true
+Number.isInteger(Math.PI); // false
+Number.isInteger(-100000); // true
+Number.isInteger(NaN);     // false
+Number.isInteger(0);       // true
+Number.isInteger("10");    // false
+
+ +

Polyfill

+ +
Number.isInteger = Number.isInteger || function(value) {
+    return typeof value === "number" &&
+           isFinite(value) &&
+           Math.floor(value) === value;
+};
+
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('ES6', '#sec-number.isinteger', 'Number.isInteger')}}{{Spec2('ES6')}}Definição inicial.
+ +

Compatibilidade dos browsers

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FuncionalidadeChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{CompatVersionUnknown}}{{CompatGeckoDesktop("16")}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FuncionalidadeAndroidChrome para AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile("16")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

Ver também

+ + diff --git a/files/pt-pt/web/javascript/reference/global_objects/number/isnan/index.html b/files/pt-pt/web/javascript/reference/global_objects/number/isnan/index.html 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 +--- +
{{JSRef}}
+ +

O método Number.isNaN() determina se o valor passado é {{jsxref("Global_Objects/NaN", "NaN")}}. Esta é uma versão mais robusta que {{jsxref("Global_Objects/isNaN", "isNaN()")}}.

+ +

Sintaxe

+ +
Number.isNaN(valor)
+ +

Parâmetros

+ +
+
valor
+
O valor a ser testado se é {{jsxref("Global_Objects/NaN", "NaN")}}.
+
+ +

Descrição

+ +

Due to both equality operators, {{jsxref("Operators/Comparison_Operators", "==", "#Equality")}} and {{jsxref("Operators/Comparison_Operators", "===", "#Identity")}}, evaluating to false when checking if {{jsxref("Global_Objects/NaN", "NaN")}} is {{jsxref("Global_Objects/NaN", "NaN")}}, the function Number.isNaN() has become necessary. This situation is unlike all other possible value comparisons in JavaScript.

+ +

In comparison to the global {{jsxref("Global_Objects/isNaN", "isNaN()")}} function, Number.isNaN() doesn't suffer the problem of forcefully converting the parameter to a number. This means it is now safe to pass values that would normally convert to {{jsxref("Global_Objects/NaN", "NaN")}}, but aren't actually the same value as {{jsxref("Global_Objects/NaN", "NaN")}}. This also means that only values of the type number, that are also {{jsxref("Global_Objects/NaN", "NaN")}}, return true.

+ +

Exemplos

+ +
Number.isNaN(NaN);        // true
+Number.isNaN(Number.NaN); // true
+Number.isNaN(0 / 0)       // true
+
+// e.g. these would have been true with global isNaN()
+Number.isNaN("NaN");      // false
+Number.isNaN(undefined);  // false
+Number.isNaN({});         // false
+Number.isNaN("blabla");   // false
+
+// These all return false
+Number.isNaN(true);
+Number.isNaN(null);
+Number.isNaN(37);
+Number.isNaN("37");
+Number.isNaN("37.37");
+Number.isNaN("");
+Number.isNaN(" ");
+
+ +

Polyfill

+ +
Number.isNaN = Number.isNaN || function(value) {
+    return typeof value === "number" && isNaN(value);
+}
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('ES6', '#sec-number.isnan', 'Number.isnan')}}{{Spec2('ES6')}}Definição inicial.
+ +

Compatibilidade dos browsers

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FuncionalidadeChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("25")}}{{CompatGeckoDesktop("15")}}{{CompatNo}}{{CompatVersionUnknown}}9
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FuncionalidadeAndroidChrome para AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatUnknown}}{{CompatGeckoMobile("15")}}{{CompatNo}}{{CompatNo}}iOS 9+
+
+ +

Ver também

+ + diff --git a/files/pt-pt/web/javascript/reference/global_objects/number/max_value/index.html b/files/pt-pt/web/javascript/reference/global_objects/number/max_value/index.html 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 +--- +
{{JSRef}}
+ +

A propriedade Number.MAX_VALUE representa o máximo valor numérico representável em JavaScript.

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

Descrição

+ +

A propriedade MAX_VALUE tem um valor aproximado de 1.79E+308. Valores maiores do que MAX_VALUE são representados como "Infinity".

+ +

Dado que MAX_VALUE é uma propriedade estática (static) de {{jsxref("Number")}}, tu deves sempre usá-la na forma Number.MAX_VALUE, em vez de na forma de uma propriedade de um objecto {{jsxref("Number")}}  que tenhas criado.

+ +

Exemplos

+ +

Usando MAX_VALUE

+ +

O seguinte código multiplica dois valores numéricos. Se o resultado for inferior ou igual a MAX_VALUE, a função func1 é chamada; senão será chamada a função func2.

+ +
if (num1 * num2 <= Number.MAX_VALUE) {
+  func1();
+} else {
+  func2();
+}
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Definição inicial. Implementado em JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.7.3.2', 'Number.MAX_VALUE')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-number.max_value', 'Number.MAX_VALUE')}}{{Spec2('ES6')}} 
+ +

Compatibilidade dos browsers

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FuncionalidadeChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FuncionalidadeAndroidChrome para AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Ver também

+ + diff --git a/files/pt-pt/web/javascript/reference/global_objects/number/min_value/index.html b/files/pt-pt/web/javascript/reference/global_objects/number/min_value/index.html 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 +--- +
{{JSRef}}
+ +

A propriedade Number.MIN_VALUE representa o mínimo valor numérico representável em JavaScript.

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

Descrição

+ +

A propriedade MIN_VALUE representa o valor mais próximo de 0 (zero), não negativo, que o JavaScript consegue representar.

+ +

A propriedade MIN_VALUE tem um valor aproximado de 5e-324. Valores menores do que MIN_VALUE ("underflow values") são são convertidos para 0 (zero).

+ +

Dado que MIN_VALUE é uma propriedade estática (static) de {{jsxref("Number")}}, tu deves sempre usá-la na forma Number.MIN_VALUE, em vez de na forma de uma propriedade de um objecto {{jsxref("Number")}} que tenhas criado.

+ +

Exemplos

+ +

Usando MIN_VALUE

+ +

O seguinte código divide dois valores numéricos. Se o resultado for superior ou igual a MIN_VALUE, a função func1 é chamada; senão será chamada a função func2.

+ +
if (num1 / num2 >= Number.MIN_VALUE) {
+  func1();
+} else {
+  func2();
+}
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.7.3.3', 'Number.MIN_VALUE')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-number.min_value', 'Number.MIN_VALUE')}}{{Spec2('ES6')}} 
+ +

Compatibilidade dos browsers

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FuncionalidadeChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FuncionalidadeAndroidChrome para AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Ver também

+ + diff --git a/files/pt-pt/web/javascript/reference/global_objects/number/nan/index.html b/files/pt-pt/web/javascript/reference/global_objects/number/nan/index.html 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 +--- +
{{JSRef}}
+ +

A propriedade Number.NaN representa um Não-Número. Equivalente a {{jsxref("NaN")}}.

+ +

Não precisas de criar um objecto {{jsxref("Number")}} para aceder a esta propriedade estática (static) (usa Number.NaN).

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

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('ES1')}}{{Spec2('ES1')}}Definição inicial. Implementado no JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.7.3.4', 'Number.NaN')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-number.nan', 'Number.NaN')}}{{Spec2('ES6')}} 
+ +

Compatibilidade dos browsers

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FuncionalidadeChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FuncionalidadeAndroidChrome para AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Ver também

+ + diff --git a/files/pt-pt/web/javascript/reference/global_objects/number/negative_infinity/index.html b/files/pt-pt/web/javascript/reference/global_objects/number/negative_infinity/index.html 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 +--- +
{{JSRef}}
+ +

A propriedade Number.NEGATIVE_INFINITY representa o valor negativo Infinito.

+ +

Não tem de criar um objecto {{jsxref("Number")}} para aceder a esta propriedade estática (usa Number.NEGATIVE_INFINITY).

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

Descrição

+ +

O valor de Number.NEGATIVE_INFINITY é o mesmo que o valor negativo da propriedade {{jsxref("Infinity")}} do objeto global.

+ +

Este valor comporta-se de forma ligeiramente diferente do infinito matemático:

+ + + +

Pode usar a propriedade Number.NEGATIVE_INFINITY para indicar uma condição de erro numa situação em que, no caso de sucesso, é retornado um valor finito.

+ +

Exemplos

+ +

Usando NEGATIVE_INFINITY

+ +

No seguinte exemplo, é atribuído à variável smallNumber um valor inferior ao valor mínimo. Quando a linha de código {{jsxref("Statements/if...else", "if")}} é executada, a variável smallNumber tem o valor -Infinity, então é atribuída à mesma variável um valor finito antes de continuar.

+ +
var smallNumber = (-Number.MAX_VALUE) * 2;
+
+if (smallNumber == Number.NEGATIVE_INFINITY) {
+  smallNumber = returnFinite();
+}
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.7.3.5', 'Number.NEGATIVE_INFINITY')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-number.negative_infinity', 'Number.NEGATIVE_INFINITY')}}{{Spec2('ES6')}}
+ +

Compatibilidade

+ + + +

{{Compat("javascript.builtins.Number.NEGATIVE_INFINITY")}}

+ +

Ver também

+ + diff --git a/files/pt-pt/web/javascript/reference/global_objects/number/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 +--- +
{{JSRef}}
+ +

A propriedade Number.prototype representa o protótipo (prototype) para o constructor de {{jsxref("Number")}}.

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

Descrição

+ +

Todas as instâncias de {{jsxref("Number")}} herdam de Number.prototype. O objecto protótipo (prototype) do constructor de {{jsxref("Number")}} pode ser modificado para afectar todas as instâncias de {{jsxref( "Number")}}.

+ +

Propriedades

+ +
+
Number.prototype.constructor
+
Retorna a função criadora das instâncias deste objecto. Por predifinição este é o objecto {{jsxref("Number")}}.
+
+ +

Métodos

+ +
+
{{jsxref("Number.prototype.toExponential()")}}
+
Retorna uma representação em string do número em notação científica.
+
{{jsxref("Number.prototype.toFixed()")}}
+
Retorna uma representação em string do número em notação de ponto fixo.
+
{{jsxref("Number.prototype.toLocaleString()")}}
+
Retorna uma string do número numa representação sensível à linguagem. Faz override do método {{jsxref("Object.prototype.toLocaleString()")}}.
+
{{jsxref("Number.prototype.toPrecision()")}}
+
Retorna uma representação em string do número numa precisão especificada em ponto fixo ou notação científica.
+
{{jsxref("Number.prototype.toSource()")}} {{non-standard_inline}}
+
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()")}}.
+
{{jsxref("Number.prototype.toString()")}}
+
Retorna uma representação em string do objecto especificado na base especificada. Faz override ao método {{jsxref("Object.prototype.toString()")}}.
+
{{jsxref("Number.prototype.valueOf()")}}
+
Retorna o valor primitivo do objecto especificado. Faz override ao método {{jsxref("Object.prototype.valueOf()")}}.
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('ES1')}}{{Spec2('ES1')}}Definição Inicial. Implementado em  JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.7.4', 'Number')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-properties-of-the-number-prototype-object', 'Number')}}{{Spec2('ES6')}} 
+ +

Compatibilidade dos browsers

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FuncionalidadeChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FuncionalidadeAndroidChrome para AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Ver também

+ + diff --git a/files/pt-pt/web/javascript/reference/global_objects/number/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 +--- +
{{JSRef}}
+ +

O método toString() retorna  uma string com o valor do objecto {{jsxref("Number")}} especificado.

+ +

Sintaxe

+ +
numObj.toString([radix])
+ +

Parâmetros

+ +
+
base
+
Opcional. Um inteiro entre [2, 36] especificando a base usada para representar o valor númerico.
+
+ +

Erros possíveis

+ +
+
{{jsxref("RangeError")}}
+
Se o valor do parâmetro base não estiver entre [2, 36], o erro {{jsxref("RangeError")}} é lançado.
+
+ +

Descrição

+ +

O objecto {{jsxref("Number")}} faz override ao método toString() do objecto {{jsxref("Object")}}; não herda de {{jsxref("Object.prototype.toString()")}}. Para os objectos {{jsxref( "Number")}}, o método toString() retorna uma representação em string do ojecto na base especificada.

+ +

O método toString() analisa o seu primeiro argumento e tenta retornar uma representação em string na base especificada. Para bases superiores a 10, as letras do alfabeto representam numerais maiores do que 9 (por ordem alfabética: a, b, c ...). Por exemplo, para números hexadecimais (base 16) são usadasa as letras do alfabeto até f.

+ +

Se a base não for especificada, o seu valor assumido é 10.

+ +

Se o numObj tem um valor negativo (< 0), o sinal é preservado. O mesmo se aplica se a base tiver o valor 2; a string retornada é a representação positiva do binário de numObj precedida pelo sinal negativo (-), e não complement para 2 de numObj.

+ +

Exemplos

+ +

Usando toString

+ +
var count = 10;
+
+console.log(count.toString());    // imprime '10'
+console.log((17).toString());     // imprime '17'
+
+var x = 6;
+
+console.log(x.toString(2));       // imprime '110'
+console.log((254).toString(16));  // imprime 'fe'
+
+console.log((-10).toString(2));   // imprime '-1010'
+console.log((-0xff).toString(2)); // imprime'-11111111'
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Definição inicial. Implementado em JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.7.4.2', 'Number.prototype.tostring')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-number.prototype.tostring', 'Number.prototype.tostring')}}{{Spec2('ES6')}} 
+ +

Compatibilidade dos browsers

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FuncionalidadeChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FuncionalidadeAndroidChrome para AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
BSuporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Ver também

+ + diff --git a/files/pt-pt/web/javascript/reference/global_objects/object/hasownproperty/index.html b/files/pt-pt/web/javascript/reference/global_objects/object/hasownproperty/index.html 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 +--- +
{{JSRef}}
+ +

O método hasOwnProperty() retorna um booleano indicando se o objeto tem a propriedade especificada.

+ +

Sintaxe

+ +
obj.hasOwnProperty(prop)
+ +

Parâmetros

+ +
+
prop
+
O nome da propriedade para testar.
+
+ +

Descrição

+ +

Cada objecto descendente de {{jsxref("Object")}} herda o método hasOwnProperty. Este método pode ser usado para determinar se um objecto contém a propriedade especificada como uma propriedade direta desse objeto; ao contrário do operador {{jsxref("Operators/in", "in")}}, este método não verifica a cadeia de objetos do protótipo.

+ +

Exemplos

+ +

Usando hasOwnProperty para testar a existência de uma propriedade

+ +

O seguinte exemplo determina se o objecto "o" contém a propriedade "prop":

+ +
o = new Object();
+o.prop = 'existe';
+
+function changeO() {
+  o.newprop = o.prop;
+  delete o.prop;
+}
+
+o.hasOwnProperty('prop');   // retorna true
+changeO();
+o.hasOwnProperty('prop');   // retorna false
+
+ +

Direto versus propriedades herdadas

+ +

O seguinte exemplo diferencia entre propriedades diretas e propriedades herdadas através da cadeia de protótipos:

+ +
o = new Object();
+o.prop = 'existe';
+o.hasOwnProperty('prop');             // retorna true
+o.hasOwnProperty('toString');         // retorna false
+o.hasOwnProperty('hasOwnProperty');   // retorna false
+
+ +

Iteração entre as propriedades de um objeto

+ +

O seguinte exemplo mostra como iterar entre as propriedades de um objeto sem executar em propriedades herdadas. Note que o ciclo {{jsxref("Statements/for...in", "for...in")}}  já está apenas repetindo itens enumeráveis então um não devia assumir baseado na falta de propriedades não-enumeráveis mostrado no ciclo que hasOwnProperty em si é estritamente limitado aos itens enumeráveis (como com {{jsxref("Object.getOwnPropertyNames()")}}).

+ +
var buz = {
+  fog: 'stack'
+};
+
+for (var name in buz) {
+  if (buz.hasOwnProperty(name)) {
+    console.log('Isto é fog (' + name + ') com certeza. Valor: ' + buz[name]);
+  }
+  else {
+    console.log(name); // toString ou outra coisa
+  }
+}
+
+ +

Usando hasOwnProperty como um nome de uma propriedade

+ +

JavaScript não protege a propriedade hasOwnProperty; assim, se a possibilidade existe de um objeto poder ter uma propriedade com este nome, é necessário usar um hasOwnProperty externo para obter resultados corretos:

+ +
var foo = {
+  hasOwnProperty: function() {
+    return false;
+  },
+  bar: 'Aqui os dragões'
+};
+
+foo.hasOwnProperty('bar'); // sempre retornará false
+
+// Use outro objeto hasOwnProperty e chame-o com 'this' definido como foo
+({}).hasOwnProperty.call(foo, 'bar'); // true
+
+// É também possível usar a propriedade hasOwnProperty através do protótipo do objeto para este propósito
+Object.prototype.hasOwnProperty.call(foo, 'bar'); // true
+
+ +

Note que no último caso, não há objetos recém-criados.

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('ES3')}}{{Spec2('ES3')}}Definição inicial. Implementado em JavaScript 1.5.
{{SpecName('ES5.1', '#sec-15.2.4.5', 'Object.prototype.hasOwnProperty')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-object.prototype.hasownproperty', 'Object.prototype.hasOwnProperty')}}{{Spec2('ES6')}} 
+ +

Compatibilidade entre browsers

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidChrome para AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Veja também

+ + diff --git a/files/pt-pt/web/javascript/reference/global_objects/object/index.html b/files/pt-pt/web/javascript/reference/global_objects/object/index.html 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 +--- +
{{JSRef}}
+ +

o construtor Object cria um wrapper de objeto.

+ +

Sintaxe

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

Parâmetros

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

Descrição

+ +

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

+ +

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

+ +

See also the object initializer / literal syntax.

+ +

Propriedades de um construtor Object

+ +
+
Object.length
+
Tem um valor de 1.
+
{{jsxref("Object.prototype")}}
+
Permite a adição de propriedades para todos os objetos do tipo Object.
+
+ +

Métodos de um construtor Object

+ +
+
{{jsxref("Object.assign()")}}
+
Copies the values of all enumerable own properties from one or more source objects to a target object.
+
{{jsxref("Object.create()")}}
+
Creates a new object with the specified prototype object and properties.
+
{{jsxref("Object.defineProperty()")}}
+
Adds the named property described by a given descriptor to an object.
+
{{jsxref("Object.defineProperties()")}}
+
Adds the named properties described by the given descriptors to an object.
+
{{jsxref("Object.entries()")}}
+
Returns an array containing all of the [key, value] pairs of a given object's own enumerable string properties.
+
{{jsxref("Object.freeze()")}}
+
Freezes an object: other code can't delete or change any properties.
+
{{jsxref("Object.fromEntries()")}}
+
Returns a new object from an iterable of key-value pairs (reverses {{jsxref("Object.entries")}}).
+
{{jsxref("Object.getOwnPropertyDescriptor()")}}
+
Returns a property descriptor for a named property on an object.
+
{{jsxref("Object.getOwnPropertyDescriptors()")}}
+
Returns an object containing all own property descriptors for an object.
+
{{jsxref("Object.getOwnPropertyNames()")}}
+
Returns an array containing the names of all of the given object's own enumerable and non-enumerable properties.
+
{{jsxref("Object.getOwnPropertySymbols()")}}
+
Returns an array of all symbol properties found directly upon a given object.
+
{{jsxref("Object.getPrototypeOf()")}}
+
Returns the prototype of the specified object.
+
{{jsxref("Object.is()")}}
+
Compares if two values are the same value. Equates all NaN values (which differs from both Abstract Equality Comparison and Strict Equality Comparison).
+
{{jsxref("Object.isExtensible()")}}
+
Determines if extending of an object is allowed.
+
{{jsxref("Object.isFrozen()")}}
+
Determines if an object was frozen.
+
{{jsxref("Object.isSealed()")}}
+
Determines if an object is sealed.
+
{{jsxref("Object.keys()")}}
+
Returns an array containing the names of all of the given object's own enumerable string properties.
+
{{jsxref("Object.preventExtensions()")}}
+
Prevents any extensions of an object.
+
{{jsxref("Object.seal()")}}
+
Prevents other code from deleting properties of an object.
+
{{jsxref("Object.setPrototypeOf()")}}
+
Sets the prototype (i.e., the internal [[Prototype]] property).
+
{{jsxref("Object.values()")}}
+
Returns an array containing the values that correspond to all of a given object's own enumerable string properties.
+
+ +

Instâcias de Object e objeto protótipo Object

+ +

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

+ +

Propriedades

+ +
{{page('//pt-PT/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype', 'Propriedades') }}
+ +

Métodos

+ +
{{page('//pt-PT/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype', 'Métodos') }}
+ +

Deleting a property from an object

+ +

There isn't any method in an Object itself to delete its own properties (e.g. like Map.prototype.delete()). To do so one has to use the delete operator.

+ +

Exemplos

+ +

Using Object given undefined and null types

+ +

The following examples store an empty Object object in o:

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

Using Object to create Boolean objects

+ +

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

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

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.2', 'Object')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-object-objects', 'Object')}}{{Spec2('ES6')}}Added Object.assign, Object.getOwnPropertySymbols, Object.setPrototypeOf, Object.is
{{SpecName('ESDraft', '#sec-object-objects', 'Object')}}{{Spec2('ESDraft')}}Added Object.entries, Object.values and Object.getOwnPropertyDescriptors.
+ +

Compatibilidade de navegador

+ +
+ + +

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

+
+ +

See also

+ + diff --git a/files/pt-pt/web/javascript/reference/global_objects/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 +--- +
{{JSRef}}
+ +

A propriedade Object.prototype representa o prototype object {{jsxref("Object","Objeto")}} .

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

Descrição

+ +

Nearly all objects in JavaScript are instances of {{jsxref("Object")}}; a typical object inherits properties (including methods) from Object.prototype, although these properties may be shadowed (a.k.a. overridden). However, an Object 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")}}).

+ +

Changes to the Object prototype object are seen by all 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.

+ +

Propriedades

+ +
+
{{jsxref("Object.prototype.constructor")}}
+
Specifies the function that creates an object's prototype.
+
{{jsxref("Object.prototype.__proto__")}} {{non-standard_inline}}
+
Points to the object which was used as prototype when the object was instantiated.
+
{{jsxref("Object.prototype.__noSuchMethod__")}} {{non-standard_inline}}
+
Allows a function to be defined that will be executed when an undefined object member is called as a method.
+
{{jsxref("Object.prototype.count","Object.prototype.__count__")}} {{obsolete_inline}}
+
Used to return the number of enumerable properties directly on a user-defined object, but has been removed.
+
{{jsxref("Object.prototype.parent","Object.prototype.__parent__")}} {{obsolete_inline}}
+
Used to point to an object's context, but has been removed.
+
+ +

Métodos

+ +
+
{{jsxref("Object.prototype.__defineGetter__()")}} {{non-standard_inline}} {{deprecated_inline}}
+
Associates a function with a property that, when accessed, executes that function and returns its return value.
+
{{jsxref("Object.prototype.__defineSetter__()")}} {{non-standard_inline}} {{deprecated_inline}}
+
Associates a function with a property that, when set, executes that function which modifies the property.
+
{{jsxref("Object.prototype.__lookupGetter__()")}} {{non-standard_inline}} {{deprecated_inline}}
+
Returns the function associated with the specified property by the {{jsxref("Object.prototype.__defineGetter__()", "__defineGetter__()")}} method.
+
{{jsxref("Object.prototype.__lookupSetter__()")}} {{non-standard_inline}} {{deprecated_inline}}
+
Returns the function associated with the specified property by the {{jsxref("Object.prototype.__defineSetter__()", "__defineSetter__()")}} method.
+
{{jsxref("Object.prototype.hasOwnProperty()")}}
+
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.
+
{{jsxref("Object.prototype.isPrototypeOf()")}}
+
Returns a boolean indicating whether the object this method is called upon is in the prototype chain of the specified object.
+
{{jsxref("Object.prototype.propertyIsEnumerable()")}}
+
Returns a boolean indicating if the internal ECMAScript [[Enumerable]] attribute is set.
+
{{jsxref("Object.prototype.toSource()")}} {{non-standard_inline}}
+
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.
+
{{jsxref("Object.prototype.toLocaleString()")}}
+
Calls {{jsxref("Object.toString", "toString()")}}.
+
{{jsxref("Object.prototype.toString()")}}
+
Returns a string representation of the object.
+
{{jsxref("Object.prototype.unwatch()")}} {{non-standard_inline}}
+
Removes a watchpoint from a property of the object.
+
{{jsxref("Object.prototype.valueOf()")}}
+
Returns the primitive value of the specified object.
+
{{jsxref("Object.prototype.watch()")}} {{non-standard_inline}}
+
Adds a watchpoint to a property of the object.
+
{{jsxref("Object.prototype.eval()")}} {{obsolete_inline}}
+
Used to evaluate a string of JavaScript code in the context of the specified object, but has been removed.
+
+ +

Exemplos

+ +

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.

+ +

When a function is called, the arguments to the call are held in the array-like "variable" arguments. 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.

+ +
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);
+  }
+}
+
+ +

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:

+ +
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();
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.2.3.1', 'Object.prototype')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-object.prototype', 'Object.prototype')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-object.prototype', 'Object.prototype')}}{{Spec2('ESDraft')}} 
+ +

Compatibilidade de navegador

+ +
+ + +

{{Compat("javascript.builtins.Object.prototype")}}

+
+ +

Consultar também

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

O objeto global String é um construtor de strings ou sequência de carateres.

+ +

Sintaxe

+ +

Os literais de string assumem as formas:

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

As Strings podem também ser criadas usando o objecto global string directamente:

+ +
String(thing)
+new String(thing)
+ +

Parâmetros

+ +
+
thing
+
Qualquer parâmetro para ser convertido numa string.
+
+ +

Strings modelo

+ +

A partir de ECMAScript 2015, os literais de strings podem também ser chamados de Modelo strings:

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

Notação Escape

+ +

Além dos carateres regulares e imprmiveis, os carateres especiais também podem ser codificados com notação escape:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CódigoResultado
\XXX (XXX = 1 - 3 octal digits; range of 0 - 377)ISO-8859-1 character / Unicode code point between U+0000 and U+00FF
\'Aspas simples
\"Aspas duplas
\\Barra invertida
\nNova linha
\rcarriage return
\vTab vertical
\tTab
\bbackspace
\fform feed
\uXXXX (XXXX = 4 hex digits; range of 0x0000 - 0xFFFF)UTF-16 code unit / Unicode code point between U+0000 and U+FFFF
\u{X} ... \u{XXXXXX} (X…XXXXXX = 1 - 6 hex digits; range of 0x0 - 0x10FFFF)UTF-32 code unit / Unicode code point between U+0000 and U+10FFFF {{experimental_inline}}
\xXX (XX = 2 hex digits; range of 0x00 - 0xFF)ISO-8859-1 character / Unicode code point between U+0000 and U+00FF
+ +
+

Note: Ao contrário de algumas outras linguagens, o Javascript não faz distinção entre strings com aspas simples e aspas duplas; Portanto a notação "escape" funciona em strings independente se foi utilizada aspas simples, ou aspas duplas na criação.

+
+ +

Strings literais longas

+ +

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

+ +

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

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

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

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

Both of these result in identical strings being created.

+ +

Descrição

+ +

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

+ +

Acesso de caráter

+ +

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

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

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

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

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

+ +

Comparação de strings

+ +

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

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

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

+ +

Distinção entre string primitivas e objetos String

+ +

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

+ +

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

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

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

+ +
+

Nota: a == b compares the strings in a and b for being equal in the usual case-sensitive way. If you wish to compare without regard to upper or lower case characters, use a function similar to this:

+ +

function isEqual(str1, str2)
+     {
+     return str1.toUpperCase()===str2.toUpperCase();
+     } // isEqual

+ +

Upper case is used instead of lower case in this function due to problems with certain UTF-8 character conversions.

+
+ +

Distinção entre string primitivas e objetos String

+ +

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

+ +

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

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

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

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

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

+ +

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

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

Propriedades

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

Métodos

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

Instâncias de String

+ +

Propriedades

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

Métodos

+ +

Methods unrelated to HTML

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

HTML wrapper methods

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

Exemplos

+ +

Conversão de String

+ +

It's possible to use String as a more reliable {{jsxref("String.prototype.toString()", "toString()")}} alternative, as it works when used on {{jsxref("null")}}, {{jsxref("undefined")}}, and on {{jsxref("Symbol", "symbols")}}. For example:

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

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('ESDraft', '#sec-string-objects', 'String')}}{{Spec2('ESDraft')}}
{{SpecName('ES2015', '#sec-string-objects', 'String')}}{{Spec2('ES2015')}}
{{SpecName('ES5.1', '#sec-15.5', 'String')}}{{Spec2('ES5.1')}}
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition.
+ +

Compatibilidade de navegador

+ + + +

{{Compat("javascript.builtins.String",2)}}

+ +

Consulte também:

+ + diff --git a/files/pt-pt/web/javascript/reference/global_objects/string/indexof/index.html b/files/pt-pt/web/javascript/reference/global_objects/string/indexof/index.html 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 +--- +
{{JSRef}}
+ +

O método indexOf() retorna o indíce da primeira ocorrência do valor especificado no objeto {{jsxref("String")}}, começando a procura a partir de fromIndex. Retorna -1 se o valor não for encontrado.

+ +

Sintaxe

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

Parâmetros

+ +
+
searchValue
+
Uma string com o valor pelo qual se procura.
+
fromIndex {{optional_inline}}
+
O ponto da string a partir do qual a procura deverá começar. Pode ter o valor de um qualquer inteiro. O valor por predefinição é 0. Se o fromIndex < 0 a procura é feita em toda a string (o mesmo que passar o valor 0). Se fromIndex >= str.length, o método retornará -1, exceção feita quando o valor de searchValue é uma string vazia, nesse caso retorna str.length.
+
+ +

Descrição

+ +

Os caractéres numa string são indexadas da esquerda para a direita. O índice do primeira caractér é 0, e o índice do último caractér da string, chamado de stringName, é stringName.length - 1.

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

Case-sensitivity

+ +

O método indexOf() é sensível a maiúsculas e minúsculas. Por exemplo, a seguinte expressão retorna -1:

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

Verificando ocorrências

+ +

Repara que '0' não é avaliado como true e '-1' não é avaliado como false. Sendo assim, a forma correta de verificar se uma string específica existe dentro de outra string deverá ser:

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

Exemplos

+ +

Usando indexOf() e lastIndexOf()

+ +

O seguinte exemplo usa indexOf() e {{jsxref("String.prototype.lastIndexOf()", "lastIndexOf()")}} para localizar valores na string "Brave new world".

+ +
var anyString = 'Brave new world';
+
+console.log('O índice do primeiro w desde o início é ' + anyString.indexOf('w'));
+// imprime 8
+console.log('O índice do primeiro w desde o fim é ' + anyString.lastIndexOf('w'));
+// imprime 10
+
+console.log('O índice de "new" desde o início é ' + anyString.indexOf('new'));
+// imprime 6
+console.log('O índice de "new" desde o fim é ' + anyString.lastIndexOf('new'));
+// imprime 6
+
+ +

indexOf() e sensibilidade a maiúsculas e minúsculas

+ +

O seguinte exemplo define duas variáveis do tipo string. As variáveis contêm a mesma string exceto o facto da segunda string conter as todas as letras maiúsculas. O primeiro método {{domxref("console.log()")}} apresenta 19. Mas porque o método indexOf() é sensível a maiúsculas e minúsculas, a string "cheddar" não é encontrada em myCapString, logo o segundo método console.log() apresenta -1.

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

Usando indexOf() para contar as ocorrências de uma letra numa string

+ +

O seguinte exemplo atribuí à variável count o número de ocorrências da letra 'e' na string str:

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

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('ES1')}}{{Spec2('ES1')}}Definição inicial.
{{SpecName('ES5.1', '#sec-15.5.4.7', 'String.prototype.indexOf')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-string.prototype.indexof', 'String.prototype.indexOf')}}{{Spec2('ES6')}} 
+ +

Compatibilidade dos browsers

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FuncionalidadeChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FuncionalidadeAndroidChrome para AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Ver também

+ + diff --git a/files/pt-pt/web/javascript/reference/global_objects/string/length/index.html b/files/pt-pt/web/javascript/reference/global_objects/string/length/index.html 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 +--- +
{{JSRef}}
+ +

A propriedade length representa o comprimento de uma string.

+ +

Sintaxe

+ +
str.length
+ +

Descrição

+ +

Esta propriedade retorna o número de code units na string. {{interwiki("wikipedia", "UTF-16")}}, o formato usado pelo JavaScript para a string, usa um single 16-bit code unit para representar os caracteres mais comuns, mas necessita de usar two code units para os caracteres menos comuns, pelo que é possível que o valor retornado por length não seja igual ao número de caracteres numa string.

+ +

Para uma string vazia, length is 0.

+ +

A propriedade estática (static) String.length retorna o valor 1.

+ +

Exemplos

+ +

Uso simples

+ +
var x = 'Mozilla';
+var empty = '';
+
+console.log('Mozilla tem de tamanho ' + x.length + ' code units');
+/* "Mozilla tem de tamanho 7 code units" */
+
+console.log('Uma string vazia tem tamanho ' + empty.length);
+/* "Uma string vazia tem tamanho 0" */
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('ES1')}}{{Spec2('ES1')}}Definição inicial. Implementado em JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.5.5.1', 'String.prototype.length')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-properties-of-string-instances-length', 'String.prototype.length')}}{{Spec2('ES6')}} 
+ +

Compatibilidade dos browsers

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FuncionalidadeChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FuncionalidadeAndroidChrome para AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Ver também

+ + diff --git a/files/pt-pt/web/javascript/reference/global_objects/string/trim/index.html b/files/pt-pt/web/javascript/reference/global_objects/string/trim/index.html 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 +--- +
{{JSRef}}
+ +

O método trim() elimina espaço em branco de ambos os extremos dum string. Espaço em branco neste contexto são todos os caracteres que apenas representam espaço (espaço, tabulação, espaço fixo, etc.) e todos os caracteres que representam limites de linha (LF, CR, etc.).

+ +

Sintaxe

+ +
str.trim()
+ +

Valor devolvido

+ +

Um novo string que representa o string que chamou despojado do espaço em branco de ambos os extremos.

+ +

Descrição

+ +

O método trim() devolve o string despojado do espaço em branco de ambos os extremos. trim() não afecta o valor do string em si.

+ +

Exemplos

+ +

Using trim()

+ +

O exemplo que se segue mostra o string 'foo' em minúsculas:

+ +
var orig = '   foo  ';
+console.log(orig.trim()); // 'foo'
+
+// Outro exemplo de .trim() eliminando espaço em branco de apenas um lado.
+
+var orig = 'foo    ';
+console.log(orig.trim()); // 'foo'
+
+ +

Polyfill

+ +

Ao correr o código que se segue antes de qualquer outro criará trim() se não estiver nativamente disponível.

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

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('ES5.1', '#sec-15.5.4.20', 'String.prototype.trim')}}{{Spec2('ES5.1')}}Definição inicial. Implementada em JavaScript 1.8.1.
{{SpecName('ES6', '#sec-string.prototype.trim', 'String.prototype.trim')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-string.prototype.trim', 'String.prototype.trim')}}{{Spec2('ESDraft')}} 
+ +

Compatibilidade de navegadores

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.9.1")}}{{CompatIE("9")}}{{CompatOpera("10.5")}}{{CompatSafari("5")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Ver também

+ + diff --git a/files/pt-pt/web/javascript/reference/global_objects/symbol/hasinstance/index.html b/files/pt-pt/web/javascript/reference/global_objects/symbol/hasinstance/index.html 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 +--- +
{{JSRef}}
+ +

O symbol bem-conhecido Symbol.hasInstance é usado para determinar se um objecto construtor reconhece um objecto como de sua instância. O comportamento do operador {{jsxref("Operators/instanceof", "instanceof")}} pode ser customizado por este symbol.

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

Exemplos

+ +

Tu podes implementar o comportamento customizado do seu instanceof deste jeito; por exemplo:

+ +
class MyArray {
+  static [Symbol.hasInstance](instance) {
+    return this.prototype.isPrototypeOf(instance) ||
+           Array.isArray(instance);
+  }
+}
+
+console.log([] instanceof MyArray); // true
+console.log(new MyArray instanceof MyArray); // true
+console.log(new Image instanceof MyArray); // false
+
+class MySubArray extends MyArray {}
+console.log(new MySubArray instanceof MySubArray); // true
+console.log(new MySubArray instanceof MyArray); // true
+console.log(new MyArray instanceof MySubArray); // false
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES6', '#sec-symbol.hasinstance', 'Symbol.hasInstance')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-symbol.hasinstance', 'Symbol.hasInstance')}}{{Spec2('ESDraft')}} 
+ +

Compatibilidade com os navegadores

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome(51)}}{{ CompatGeckoDesktop(50) }}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatUnknown}}{{ CompatGeckoMobile(50) }}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

Veja também

+ + diff --git a/files/pt-pt/web/javascript/reference/global_objects/symbol/index.html b/files/pt-pt/web/javascript/reference/global_objects/symbol/index.html 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 +--- +
{{JSRef}}
+ +

A symbol is a unique and immutable data type. It may be used as an identifier for object properties. The Symbol object is an implicit object wrapper for the symbol {{Glossary("Primitive", "primitive data type")}}.

+ +

Syntax

+ +
Symbol([description])
+ +

Parameters

+ +
+
description {{optional_inline}}
+
Optional, string. A description of the symbol which can be used for debugging but not to access the symbol itself.
+
+ +

Description

+ +

To create a new primitive symbol, you write Symbol() with an optional string as its description:

+ +
var sym1 = Symbol();
+var sym2 = Symbol("foo");
+var sym3 = Symbol("foo");
+
+ +

The above code creates three new symbols. Note that Symbol("foo") does not coerce the string "foo" into a symbol. It creates a new symbol each time:

+ +
Symbol("foo") === Symbol("foo"); // false
+ +

The following syntax with the {{jsxref("Operators/new", "new")}} operator will throw a {{jsxref("TypeError")}}:

+ +
var sym = new Symbol(); // TypeError
+ +

This prevents authors from creating an explicit Symbol wrapper object instead of a new symbol value and might be surprising as creating explicit wrapper objects around primitive data types is generally possible (for example, new Boolean, new String and new Number).

+ +

If you really want to create a Symbol wrapper object, you can use the Object() function:

+ +
var sym = Symbol("foo");
+typeof sym;     // "symbol"
+var symObj = Object(sym);
+typeof symObj;  // "object"
+
+ +

Shared symbols in the global symbol registry

+ +

The above syntax using the Symbol() function will not create a global symbol that is available in your whole codebase. To create symbols available across files and even across realms (each of which has its own global scope), use the methods {{jsxref("Symbol.for()")}} and {{jsxref("Symbol.keyFor()")}} to set and retrieve symbols from the global symbol registry.

+ +

Finding symbol properties on objects

+ +

The method {{jsxref("Object.getOwnPropertySymbols()")}} returns an array of symbols and lets you find symbol properties on a given object. Note that every object is initialized with no own symbol properties, so that this array will be empty unless you've set symbol properties on the object.

+ +

Properties

+ +
+
Symbol.length
+
Length property whose value is 0.
+
{{jsxref("Symbol.prototype")}}
+
Represents the prototype for the Symbol constructor.
+
+ +

Well-known symbols

+ +

In addition to your own symbols, JavaScript has some built-in symbols which represent internal language behaviors which were not exposed to developers in ECMAScript 5 and before. These symbols can be accessed using the following properties:

+ +

Iteration symbols

+ +
+
{{jsxref("Symbol.iterator")}}
+
A method returning the default iterator for an object. Used by for...of.
+
+ +

Regular expression symbols

+ +
+
{{jsxref("Symbol.match")}}
+
A method that matches against a string, also used to determine if an object may be used as a regular expression. Used by {{jsxref("String.prototype.match()")}}.
+
{{jsxref("Symbol.replace")}}
+
A method that replaces matched substrings of a string. Used by {{jsxref("String.prototype.replace()")}}.
+
{{jsxref("Symbol.search")}}
+
A method that returns the index within a string that matches the regular expression. Used by {{jsxref("String.prototype.search()")}}.
+
{{jsxref("Symbol.split")}}
+
A method that splits a string at the indices that match a regular expression. Used by {{jsxref("String.prototype.split()")}}.
+
+ +

Other symbols

+ +
+
{{jsxref("Symbol.hasInstance")}}
+
A method determining if a constructor object recognizes an object as its instance. Used by {{jsxref("Operators/instanceof", "instanceof")}}.
+
{{jsxref("Symbol.isConcatSpreadable")}}
+
A Boolean value indicating if an object should be flattened to its array elements. Used by {{jsxref("Array.prototype.concat()")}}.
+
{{jsxref("Symbol.unscopables")}}
+
An object value of whose own and inherited property names are excluded from the with environment bindings of the associated object.
+
{{jsxref("Symbol.species")}}
+
A constructor function that is used to create derived objects.
+
{{jsxref("Symbol.toPrimitive")}}
+
A method converting an object to a primitive value.
+
{{jsxref("Symbol.toStringTag")}}
+
A string value used for the default description of an object. Used by {{jsxref("Object.prototype.toString()")}}.
+
+ +

Methods

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

Symbol prototype

+ +

All Symbols inherit from {{jsxref("Symbol.prototype")}}.

+ +

Properties

+ +

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

+ +

Methods

+ +

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

+ +

Examples

+ +

Using the typeof operator with symbols

+ +

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

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

Symbol type conversions

+ +

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

+ + + +

Symbols and for...in iteration

+ +

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

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

Symbols and JSON.stringify()

+ +

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

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

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

+ +

Symbol wrapper objects as property keys

+ +

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

+ +
var sym = Symbol("foo");
+var obj = {[sym]: 1};
+obj[sym];            // 1
+obj[Object(sym)];    // still 1
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES6', '#sec-symbol-objects', 'Symbol')}}{{Spec2('ES6')}}Initial definition
{{SpecName('ESDraft', '#sec-symbol-objects', 'Symbol')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome(38)}}{{CompatGeckoDesktop(36)}}{{CompatNo}}259
Symbol.iterator (@@iterator){{CompatChrome(38)}}{{CompatGeckoDesktop(36)}}{{CompatNo}}259
Symbol.unscopables (@@unscopables){{CompatChrome(38)}}{{CompatGeckoDesktop(48)}}{{CompatNo}}259
Symbol.match (@@match){{CompatChrome(50)}}{{CompatGeckoDesktop(40)}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}
Symbol.species (@@species){{CompatChrome(51)}}{{CompatGeckoDesktop(41)}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}
Symbol.toPrimitive (@@toPrimitive){{CompatChrome(48)}}{{CompatGeckoDesktop(44)}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}
Symbol.replace (@@replace){{CompatChrome(50)}}{{CompatGeckoDesktop(48)}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}
Symbol.search (@@search){{CompatChrome(50)}}{{CompatGeckoDesktop(48)}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}
Symbol.split (@@split){{CompatChrome(50)}}{{CompatGeckoDesktop(48)}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}
Symbol.isConcatSpreadable (@@isconcatspreadable){{CompatChrome(48)}}{{CompatGeckoDesktop(48)}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}
Symbol.hasInstance (@@hasInstance){{CompatChrome(51)}}{{CompatGeckoDesktop(50)}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}
Symbol.toStringTag (@@toStringTag){{CompatChrome(49)}}{{CompatGeckoDesktop(51)}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatChrome(38)}}{{CompatGeckoMobile(36)}}{{CompatNo}}259
Symbol.iterator (@@iterator){{CompatUnknown}}{{CompatChrome(38)}}{{CompatGeckoMobile(36)}}{{CompatNo}}259
Symbol.unscopables (@@unscopables){{CompatUnknown}}{{CompatChrome(38)}}{{CompatGeckoMobile(48)}}{{CompatNo}}259
Symbol.match (@@match){{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile(40)}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}
Symbol.species (@@species){{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile(41)}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}
Symbol.toPrimitive (@@toPrimitive){{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile(44)}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}
Symbol.replace (@@replace){{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile(48)}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}
Symbol.search (@@search){{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile(48)}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}
Symbol.split (@@split){{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile(48)}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}
Symbol.isConcatSpreadable (@@isconcatspreadable){{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile(48)}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}
Symbol.hasInstance (@@hasInstance){{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile(50)}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}
Symbol.toStringTag (@@toStringTag){{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile(51)}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

See also

+ + diff --git a/files/pt-pt/web/javascript/reference/index.html b/files/pt-pt/web/javascript/reference/index.html 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 +--- +
{{JsSidebar}}
+ +

Esta parte da secção de JavaScript na MDN serve como um repositório de factos sobre a linguage JavaScript. Leia mais sobre esta referência.

+ +

Integrações

+ +

Objetos integrados padrões de JavaScript, em conjunto com os seus métodos e propriedades.

+ + + + + + + + + +

Declações (Statements)

+ +

Declarações e instruções de JavaScript

+ + + + + +

Expressões e operadores

+ +

Expressões e operadores de JavaScript

+ +
+ + + + + +
+ +

Funções

+ +

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

+ + + +

Páginas adicionais de referência

+ + diff --git "a/files/pt-pt/web/javascript/reference/operadores/fun\303\247\303\243o/index.html" "b/files/pt-pt/web/javascript/reference/operadores/fun\303\247\303\243o/index.html" new file mode 100644 index 0000000000..450183b727 --- /dev/null +++ "b/files/pt-pt/web/javascript/reference/operadores/fun\303\247\303\243o/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 +--- +
{{jsSidebar("Operators")}}
+ +

A palavra-chave function  pode ser utilziada para definir uma função dentro de uma expressão.

+ +

You can also define functions using the Function constructor and a function declaration.

+ +
{{EmbedInteractiveExample("pages/js/expressions-functionexpression.html", "shorter")}}
+ + + +

Sintaxe

+ +
let myFunction = function [name]([param1[, param2[, ..., paramN]]]) {
+   statements
+};
+ +

As of ES2015, you can also use {{jsxref("Functions/Arrow_functions", "arrow functions")}}.

+ +

Parâmetros

+ +
+
name {{optional_inline}}
+
The function name. Can be omitted, in which case the function is anonymous. The name is only local to the function body.
+
paramN {{optional_inline}}
+
The name of an argument to be passed to the function.
+
statements {{optional_inline}}
+
The statements which comprise the body of the function.
+
+ +

Descrição

+ +

A function expression is very similar to and has almost the same syntax as a function declaration (see {{jsxref("Statements/function", "function statement")}} for details). The main difference between a function expression and a function declaration is the function name, which can be omitted in function expressions to create anonymous functions. A function expression can be used as an IIFE (Immediately Invoked Function Expression) which runs as soon as it is defined. See also the chapter about {{jsxref("Functions", "functions")}} for more information.

+ +

Function expression hoisting

+ +

Function expressions in JavaScript are not hoisted, unlike {{jsxref("Statements/function", "function declarations", "#Function_declaration_hoisting")}}. You can't use function expressions before you define them:

+ +
console.log(notHoisted) // undefined
+//  even though the variable name is hoisted, the definition isn't. so it's undefined.
+notHoisted(); // TypeError: notHoisted is not a function
+
+var notHoisted = function() {
+   console.log('bar');
+};
+
+ +

Named function expression

+ +

If you want to refer to the current function inside the function body, you need to create a named function expression. This name is then local only to the function body (scope). This also avoids using the non-standard {{jsxref("Functions/arguments/callee", "arguments.callee")}} property.

+ +
let math = {
+  'factit': function factorial(n) {
+    console.log(n)
+    if (n <= 1) {
+      return 1;
+    }
+    return n * factorial(n - 1);
+  }
+};
+
+math.factit(3) //3;2;1;
+
+ +

The variable the function expression is assigned to will have a name property. The name doesn't change if it's assigned to a different variable. If function name is omitted, it will be the variable name (implicit name). If function name is present, it will be the function name (explicit name). This also applies to {{jsxref("Functions/Arrow_functions", "arrow functions")}} (arrows don't have a name so you can only give the variable an implicit name).

+ +
var foo = function() {}
+foo.name // "foo"
+
+var foo2 = foo
+foo2.name // "foo"
+
+var bar = function baz() {}
+bar.name // "baz"
+
+console.log(foo === foo2); // true
+console.log(typeof baz); // undefined
+console.log(bar === baz); // false (errors because baz == undefined)
+
+ +

Exemplos

+ +

The following example defines an unnamed function and assigns it to x. The function returns the square of its argument:

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

More commonly it is used as a callback:

+ +
button.addEventListener('click', function(event) {
+    console.log('button is clicked!')
+})
+ +

Especificações

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

Compatibilidade de navegador

+ + + +

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

+ +

Consulte também 

+ + diff --git a/files/pt-pt/web/javascript/reference/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 +--- +
{{jsSidebar("Operators")}}
+ +

Este capítulo documenta todos os operadores, expressões e palavras-chave da linguagem JavaScript.

+ +

Expressões e operadores por categoria

+ +

For an alphabetical listing see the sidebar on the left.

+ +

Expressões primárias

+ +

Basic keywords and general expressions in JavaScript.

+ +
+
{{JSxRef("Operators/this", "this")}}
+
The this keyword refers to a special property of an execution context.
+
{{JSxRef("Operators/function", "function")}}
+
The function keyword defines a function expression.
+
{{JSxRef("Operators/class", "class")}}
+
The class keyword defines a class expression.
+
{{JSxRef("Operators/function*", "function*")}}
+
The function* keyword defines a generator function expression.
+
{{JSxRef("Operators/yield", "yield")}}
+
Pause and resume a generator function.
+
{{JSxRef("Operators/yield*", "yield*")}}
+
Delegate to another generator function or iterable object.
+
{{JSxRef("Operators/async_function", "async function")}}
+
The async function defines an async function expression.
+
{{JSxRef("Operators/await", "await")}}
+
Pause and resume an async function and wait for the promise's resolution/rejection.
+
{{JSxRef("Global_Objects/Array", "[]")}}
+
Array initializer/literal syntax.
+
{{JSxRef("Operators/Object_initializer", "{}")}}
+
Object initializer/literal syntax.
+
{{JSxRef("Global_Objects/RegExp", "/ab+c/i")}}
+
Regular expression literal syntax.
+
{{JSxRef("Operators/Grouping", "( )")}}
+
Grouping operator.
+
+ +

Expressões "Left-hand-side"

+ +

Left values are the destination of an assignment.

+ +
+
{{jsxref("Operators/Property_accessors", "Property accessors", "", 1)}}
+
Member operators provide access to a property or method of an object
+ (object.property and object["property"]).
+
{{jsxref("Operators/new", "new")}}
+
The new operator creates an instance of a constructor.
+
new.target
+
In constructors, new.target refers to the constructor that was invoked by {{jsxref("Operators/new", "new")}}.
+
{{jsxref("Operators/super", "super")}}
+
The super keyword calls the parent constructor.
+
{{jsxref("Operators/Spread_operator", "...obj")}}
+
The spread operator allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) are expected.
+
+ +

Aumento e diminuição

+ +

Postfix/prefix increment and postfix/prefix decrement operators.

+ +
+
{{jsxref("Operators/Arithmetic_Operators", "A++", "#Increment")}}
+
Postfix increment operator.
+
{{jsxref("Operators/Arithmetic_Operators", "A--", "#Decrement")}}
+
Postfix decrement operator.
+
{{jsxref("Operators/Arithmetic_Operators", "++A", "#Increment")}}
+
Prefix increment operator.
+
{{jsxref("Operators/Arithmetic_Operators", "--A", "#Decrement")}}
+
Prefix decrement operator.
+
+ +

Operadores unários

+ +

A unary operation is operation with only one operand.

+ +
+
{{jsxref("Operators/delete", "delete")}}
+
The delete operator deletes a property from an object.
+
{{jsxref("Operators/void", "void")}}
+
The void operator discards an expression's return value.
+
{{jsxref("Operators/typeof", "typeof")}}
+
The typeof operator determines the type of a given object.
+
{{jsxref("Operators/Arithmetic_Operators", "+", "#Unary_plus")}}
+
The unary plus operator converts its operand to Number type.
+
{{jsxref("Operators/Arithmetic_Operators", "-", "#Unary_negation")}}
+
The unary negation operator converts its operand to Number type and then negates it.
+
{{jsxref("Operators/Bitwise_Operators", "~", "#Bitwise_NOT")}}
+
Bitwise NOT operator.
+
{{jsxref("Operators/Logical_Operators", "!", "#Logical_NOT")}}
+
Logical NOT operator.
+
+ +

Operadores de aritmética

+ +

Arithmetic operators take numerical values (either literals or variables) as their operands and return a single numerical value.

+ +
+
{{jsxref("Operators/Arithmetic_Operators", "+", "#Addition")}}
+
Addition operator.
+
{{jsxref("Operators/Arithmetic_Operators", "-", "#Subtraction")}}
+
Subtraction operator.
+
{{jsxref("Operators/Arithmetic_Operators", "/", "#Division")}}
+
Division operator.
+
{{jsxref("Operators/Arithmetic_Operators", "*", "#Multiplication")}}
+
Multiplication operator.
+
{{jsxref("Operators/Arithmetic_Operators", "%", "#Remainder")}}
+
Remainder operator.
+
+ +
+
{{JSxRef("Operators/Arithmetic_Operators", "**", "#Exponentiation")}}
+
Exponentiation operator.
+
+ +

Operadores relacionais

+ +

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

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

Nota: => não é um operador, mas a notação para funções seta (arrow).

+
+ +

Operadores de equality

+ +

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

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

Bitwise shift operators

+ +

Operations to shift all bits of the operand.

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

Operadores de binário bitwise

+ +

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

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

Operadores de binário logical

+ +

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

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

Operdor condicional (ternário)

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

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

+
+
+ +

Operadores de Assignment

+ +

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

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

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

+
+
+ +

Operador de aspas

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

Funcionalidades não padrão

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

Especificações

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

Compatibilidade de navegador

+ + + +

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

+ +

Consulte também

+ + diff --git a/files/pt-pt/web/javascript/reference/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 +--- +
Operador {{jsSidebar("Operators")}}
+ +

operador vírgula (,) avalia cada um dos seus operandos (da esquerda para a direita) e devolve o valor do último operando. This lets you create a compound expression in which multiple expressions are evaluated, with the compound expression's final value being the value of the rightmost of its member expressions. This is commonly used to provide multiple parameters to a for loop.

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

Sintaxe

+ +
expr1, expr2, expr3...
+ +

Parâmetros

+ +
+
expr1, expr2, expr3...
+
One or more expressions, the last of which is returned as the value of the compound expression.
+
+ +

Notas de utilização

+ +

You can use the comma operator when you want to include multiple expressions in a location that requires a single expression. The most common usage of this operator is to supply multiple parameters in a for loop.

+ +

The comma operator is fully different from the comma within arrays, objects, and function arguments and parameters.

+ +

Exemplos

+ +

If a is a 2-dimensional array with 10 elements on each side, the following code uses the comma operator to increment i and decrement j at once.

+ +

The following code prints the values of the diagonal elements in the array:

+ +
for (var i = 0, j = 9; i <= 9; i++, j--)
+  console.log('a[' + i + '][' + j + '] = ' + a[i][j]);
+ +

Note that the comma operators in assignments may appear not to have the normal effect of comma operators because they don't exist within an expression. In the following example, a is set to the value of b = 3 (which is 3), but the c = 4 expression still evaluates and its result returned to console (i.e., 4). This is due to operator precedence and associativity.

+ +
var a, b, c;
+
+a = b = 3, c = 4; // Returns 4 in console
+console.log(a); // 3 (left-most)
+
+var x, y, z;
+
+x = (y = 5, z = 6); // Returns 6 in console
+console.log(x); // 6 (right-most)
+
+ +

Processing and then returning

+ +

Another example that one could make with comma operator is processing before returning. As stated, only the last element will be returned but all others are going to be evaluated as well. So, one could do:

+ +
function myFunc() {
+  var x = 0;
+
+  return (x += 1, x); // the same as return ++x;
+}
+ +

Especificações

+ + + + + + + + + + +
Especificação
{{SpecName('ESDraft', '#sec-comma-operator', 'Comma operator')}}
+ +

Compatibilidade de navegador

+ + + +

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

+ +

Consulte também

+ + diff --git a/files/pt-pt/web/javascript/reference/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 +--- +
{{jsSidebar("Operators")}}
+ +

A precedência de operador determina a maneira pela qual os operadores são analisados ​​em relação a cada um. Os operadores com maior precedência tornam-se operandos dos operadores com menor precedência..

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

Precedência e Associabilidade

+ +

Consider an expression describable by the representation below. Note that both OP1 and OPare fill-in-the-blanks for OPerators.

+ +
a OP b OP c
+
+ +

If OP1 and OP2 have different precedence levels (see the table below), the operator with the highest precedence goes first and associativity does not matter. Observe how multiplication has higher associativity than addition and executed first, even though addition is written first in the code.

+ +
console.log(3 + 10 * 2);   // logs 23
+console.log(3 + (10 * 2)); // logs 23 because parentheses here are superfluous
+console.log((3 + 10) * 2); // logs 26 because the parentheses change the order 
+ +

Left-associativity (left-to-right) means that it is processed as (a OP1 b) OP2 c, while right-associativity (right-to-left) means it is interpreted as a OP1 (b OP2 c). Assignment operators are right-associative, so you can write:

+ +
a = b = 5; // same as writing a = (b = 5);
+
+ +

with the expected result that a and b get the value 5. This is because the assignment operator returns the value that is assigned. First, b is set to 5. Then the a is also set to 5, the return value of b = 5, aka right operand of the assignment.

+ +

As another example, the unique exponentiation operator has right-associativity, whereas other arithmetic operators have left-associativity. It is interesting to note that, the order of evaluation is always left-to-right irregardless of associativity.

+ + + + + + + + + + + + + + + + +
CódigoResultado
+
+function echo(name, num) {
+    console.log("Evaluating the " + name + " side");
+    return num;
+}
+// Notice the division operator (/)
+console.log(echo("left", 6) / echo("right", 2));
+
+
+
+Evaluating the left side
+Evaluating the right side
+3
+
+
+
+function echo(name, num) {
+    console.log("Evaluating the " + name + " side");
+    return num;
+}
+// Notice the exponentiation operator (**)
+console.log(echo("left", 2) ** echo("right", 3));
+
+
+Evaluating the left side
+Evaluating the right side
+8
+
+ +

The difference in associativity comes into play when there are multiple operators of the same precedence. With only one operator or operators of different precedences, associativity does affect the output, as seen in the example above. In the example below, observe how associativity affects the output when multiple of the same operator are used.

+ + + + + + + + + + + + + + + + + + + + +
CódigoResultado
+
+function echo(name, num) {
+    console.log("Evaluating the " + name + " side");
+    return num;
+}
+// Notice the division operator (/)
+console.log(echo("left", 6) / echo("middle", 2) / echo("right", 3));
+
+
+
+Evaluating the left side
+Evaluating the middle side
+Evaluating the right side
+1
+
+
+
+function echo(name, num) {
+    console.log("Evaluating the " + name + " side");
+    return num;
+}
+// Notice the exponentiation operator (**)
+console.log(echo("left", 2) ** echo("middle", 3) ** echo("right", 2));
+
+
+
+Evaluating the left side
+Evaluating the middle side
+Evaluating the right side
+512
+
+
+
+function echo(name, num) {
+    console.log("Evaluating the " + name + " side");
+    return num;
+}
+// Notice the parentheses around the left and middle exponentiation
+console.log((echo("left", 2) ** echo("middle", 3)) ** echo("right", 2));
+
+
+Evaluating the left side
+Evaluating the middle side
+Evaluating the right side
+64
+
+ +

Looking at the code snippets above, 6 / 3 / 2 is the same as (6 / 3) / 2 because division is left-associative. Exponentiation, on the other hand, is right-associative, so 2 ** 3 ** 2 is the same as 2 ** (3 ** 2). Thus, doing (2 ** 3) ** 2 changes the order and results in the 64 seen in the table above.

+ +

Remember that precedence comes before associativity. So, mixing division and exponentiation, the exponentiation comes before the division. For example, 2 ** 3 / 3 ** 2 results in 0.8888888888888888 because it is the same as (2 ** 3) / (3 ** 2).

+ +

Note on Grouping and Short-Circuiting

+ +

In the table below, Grouping is listed as having the highest precedence. However, that does not always mean the expression within the grouping symbols ( … ) is evaluated first, especially when it comes to short-circuiting.

+ +

Short-circuiting is jargon for conditional evaluation. For example, in the expression a && (b + c), if a is “falsy”, then the sub-expression (b + c) will not even get evaluated, even if it is in parentheses. We could say that the logical disjunction operator (“OR”) is “short-circuited”. Along with logical disjunction, other short-circuited operators include logical conjunction (“AND”), nullish-coalescing, optional chaining, and the conditional operator. Some more examples follow.

+ +
a || (b * c);  // evaluate `a` first, then produce `a` if `a` is “truthy”
+a && (b < c);  // evaluate `a` first, then produce `a` if `a` is “falsy”
+a ?? (b || c); // evaluate `a` first, then produce `a` if `a` is not `null` and not `undefined`
+a?.b.c;        // evaluate `a` first, then produce `a` if `a` is `null` or `undefined`
+
+ +

Exemplos

+ +
3 > 2 && 2 > 1
+// returns true
+
+3 > 2 > 1
+// Returns false because 3 > 2 is true, then true is converted to 1 in inequality operators, therefore true > 1 becomes 1 > 1, which
+//  is false. Adding parentheses makes things clear: (3 > 2) > 1.
+
+
+ +

Tabela

+ +

The following table is ordered from highest (20) to lowest (1) precedence.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PrecedênciaTipo de operador (Operator)AssociatividadeOperadores individuais
20{{jsxref("Operators/Grouping", "Grouping")}}n/a( … )
19{{jsxref("Operators/Property_Accessors", "Member Access", "#Dot_notation")}}left-to-right… . …
{{jsxref("Operators/Property_Accessors", "Computed Member Access","#Bracket_notation")}}left-to-right… [ … ]
{{jsxref("Operators/new","new")}} (with argument list)n/anew … ( … )
Function Callleft-to-right… ( … )
18{{jsxref("Operators/new","new")}} (without argument list)right-to-leftnew …
17{{jsxref("Operators/Arithmetic_Operators","Postfix Increment","#Increment")}}n/a… ++
{{jsxref("Operators/Arithmetic_Operators","Postfix Decrement","#Decrement")}}… --
16Logical NOTright-to-left! …
Bitwise NOT~ …
Unary Plus+ …
Unary Negation- …
Prefix Increment++ …
Prefix Decrement-- …
typeoftypeof …
voidvoid …
deletedelete …
awaitawait …
15Exponentiationright-to-left… ** …
14Multiplicationleft-to-right… * …
Division… / …
Remainder… % …
13Additionleft-to-right… + …
Subtraction… - …
12Bitwise Left Shiftleft-to-right… << …
Bitwise Right Shift… >> …
Bitwise Unsigned Right Shift… >>> …
11Less Thanleft-to-right… < …
Less Than Or Equal… <= …
Greater Than… > …
Greater Than Or Equal… >= …
in… in …
instanceof… instanceof …
10Equalityleft-to-right… == …
Inequality… != …
Strict Equality… === …
Strict Inequality… !== …
9Bitwise ANDleft-to-right… & …
8Bitwise XORleft-to-right… ^ …
7Bitwise ORleft-to-right… | …
6Logical ANDleft-to-right… && …
5Logical ORleft-to-right… || …
4Conditionalright-to-left… ? … : …
3Assignmentright-to-left… = …
… += …
… -= …
… **= …
… *= …
… /= …
… %= …
… <<= …
… >>= …
… >>>= …
… &= …
… ^= …
… |= …
2{{jsxref("Operators/yield", "yield")}}right-to-leftyield …
{{jsxref("Operators/yield*", "yield*")}}yield* …
1Vírgula / Sequêncialeft-to-right… , …
diff --git a/files/pt-pt/web/javascript/reference/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 +--- +
{{JsSidebar}}
+ +

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

+ +

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

+ +

Onde encontrar informação sobre JavaScript

+ +

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

+ + + +

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

+ +

Estrutura da referência

+ +

In the JavaScript reference you can find the following chapters:

+ +
+
Standard built-in objects
+
This chapter documents all the JavaScript standard built-in objects, along with their methods and properties.
+
Statements and declarations
+
JavaScript applications consist of statements with an appropriate syntax. A single statement may span multiple lines. Multiple statements may occur on a single line if each statement is separated by a semicolon. This isn't a keyword, but a group of keywords.
+
Expressions and operators
+
This chapter documents all the JavaScript language operators, expressions and keywords.
+
Functions
+
Chapter about JavaScript functions.
+
Classes
+
Chapter about JavaScript classes introduced in ECMAScript 6.
+
Errors
+
Chapter about specific errors, exceptions and warnings thrown by JavaScript.
+
New in JavaScript
+
Chapter about JavaScript version history.
+
+ +

Mais páginas de referência

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