Estrutura de dados do Javascript

Tradução em progresso.

Todas as linguagens de programação têm sua própria estrutura de dados embutida, mas essa estrutura frequetemente difere uma da outra. Este artigo tenta listar os tipos de dados disponíveis na linguagem JavaScript e que propriedades eles têm. Quando possível comparações com outras linguagens serão apresentadas.

Tipagem Dinâmica

JavaScript é uma linguagem de tipagem dinâmica . Isso significa que você não necessita declarar o tipo de uma variável antes de sua atribuição. O tipo será automaticamente determinado quando o programa for processado. Isso também significa que você pode reatribuir uma mesma variável com um tipo diferente:

var foo = 42;    // foo é um Number agora
var foo = "bar"; // foo é um String agora
var foo = true;  // foo é um Boolean agora

Tipos de Dados

A última versão ECMAScript define sete tipos de dados:

Valores Primitivos

Todos os tipos exceto objetos definem valores imutáveis (valores que são incapazes de mudar). Por exemplo e diferente da linguagem C, Strings são imutáveis. Nós nos referimos a valores desses tipos como "valores primitivos".

Tipo Boolean

Boolean representa uma entidade lógica e pode ter dois valores: verdadeiro(true) ou falso(false).

Tipo Null

O tipo Null tem exatamente um valor: null(nulo). Veja null e Null para mais detalhes.

Tipo Undefined

Uma variável que não foi atribuída a um valor tem o valor undefined(indefinido). Vejs undefined e Undefined para mais detalhes.

Tipo Number

De acordo com os padrões ECMAScript, existe somente um tipo numérico. O double-precision 64-bit binary format IEEE 754 value (número entre -(253 -1) e 253 -1). Não existe um tipo específico para inteiros. Além de poderem representar números de ponto-flutuante, o tipo number possui três valores simbólicos: +Infinity, -Infinity, e NaN (não numérico).

Para verificar o maior ou o menor valor disponível dentro de +/-Infinity, você pode usar as constantes Number.MAX_VALUE ou Number.MIN_VALUE, e a partir do ECMAScript 6, você também consegue verificar se um número está dentro da região de um ponto flututante do tipo double-precision, usando Number.isSafeInteger(), como também Number.MAX_SAFE_INTEGER, e Number.MIN_SAFE_INTEGER. Fora dessa região, números inteiros em JavaScript não são mais precisos e serão uma aproximação de um número de ponto flutuante do tipo double-precission.

O tipo number possui apenas um inteiro que tem duas representações: 0 é representado como -0 e +0. ("0" é um alias para +0). Na prática, isso não gera grandes impactos. Por exemplo +0 === -0  resulta em true. Entretanto, você pode notar a diferença quando realiza uma divisão por 0:

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

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

String type

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

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

  • A substring of the original by picking individual letters or using String.substr().
  • A concatenation of two strings using the concatenation operator (+) or String.concat().

Beware of "stringly-typing" your code!

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

  • It is easy to build complex strings with concatenation.
  • Strings are easy to debug (what you see printed is always what is in the string).
  • Strings are the common denominator of a lot of APIs (input fields, local storage values, XMLHttpRequest responses when using responseText, etc.) and it can be tempting to only work with strings.

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

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

Symbol type

Symbols são novos no JavaScript ECMAScript edição 6. Um Symbol é um valor primitivo único e imutável e pode ser usado como chave de uma propriedade de Object (ver abaixo). em algumas linguagens de programação, Symbols são chamados de atoms(átomos). Você também pode compará-los à enumerações nomeadas(enum) em C. Para mais detalhes veja Symbol e o Symbol object wrapper em JavaScript.

Objects

In computer science, an object is a value in memory which is possibly referenced by an identifier.

Properties

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

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

Data property

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

Attributes of a data property
Attribute Type Description Default value
[[Value]] Any JavaScript type The value retrieved by a get access of the property. undefined
[[Writable]] Boolean If false, the property's [[Value]] can't be changed. false
[[Enumerable]] Boolean If true, the property will be enumerated in for...in loops. false
[[Configurable]] Boolean If false, the property can't be deleted and attributes other than [[Value]] and [[Writable]] can't be changed. false

Accessor property

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

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

"Normal" objects, and functions

A JavaScript object is a mapping between keys and values. Keys are strings and values can be anything. This makes objects a natural fit for hashmaps.

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

Dates

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

Indexed collections: Arrays and typed Arrays

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

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

TypedArray objects

Type Size in bytes Description Web IDL type Equivalent C type
Int8Array 1 8-bit two's complement signed integer byte int8_t
Uint8Array 1 8-bit unsigned integer octet uint8_t
Uint8ClampedArray 1 8-bit unsigned integer (clamped) octet uint8_t
Int16Array 2 16-bit two's complement signed integer short int16_t
Uint16Array 2 16-bit unsigned integer unsigned short uint16_t
Int32Array 4 32-bit two's complement signed integer long int32_t
Uint32Array 4 32-bit unsigned integer unsigned long uint32_t
Float32Array 4 32-bit IEEE floating point number unrestricted float float
Float64Array 8 64-bit IEEE floating point number unrestricted double double

Keyed collections: Maps, Sets, WeakMaps, WeakSets

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

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

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

Structured data: JSON

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

Mais objetos na biblioteca  padrão

Javascript possui uma biblioteca padrão com objetos pré-construidos.Por favor olhe a reference para descobrir mais sobre objetos.

Determinando  tipos usando o operador typeof

O operador typeof pode lhe ajudar a encontrar o tipo de sua variavel.Por favor, leia a reference page para mais detalhes e casos de uso.

Especificações

Specification Status Comment
ECMAScript 1st Edition. Standard Initial definition.
ECMAScript 5.1 (ECMA-262)
The definition of 'Types' in that specification.
Padrão  

ECMAScript 2015 (6th Edition, ECMA-262)
The definition of 'ECMAScript Data Types and Values' in that specification.

Padrão  
ECMAScript Latest Draft (ECMA-262)
The definition of 'ECMAScript Data Types and Values' in that specification.

 
Padrão em tempo real
 

See also

Etiquetas do documento e colaboradores

Etiquetas: 
 Última atualização por: HelderSi,