The Wayback Machine - https://web.archive.org/web/20150906121018/https://developer.mozilla.org/vi/docs/Web/JavaScript/Data_structures

Kiểu dữ liệu và cấu trúc dữ liệu trong Javascript

by 1 contributor:

This translation is in progress.

Tất cả các ngôn ngữ lập trình đều có cấu trúc dữ liệu dựng sẵn, nhưng mỗi ngôn ngữ thường có những kiểu cấu trúc dữ liệu khác nhau. Bài viết này sẽ có gắng liệt kê những khiệu dữ liệu dựng sẵn trong Javascript và những thuộc tính của chúng; chúng có thể được dùng để xây dựng những kiểu cấu trúc dữ liệu khác. Khi có thể, rút ra so sánh với những ngôn ngữ khác.

Kiểu động

JavaScript là một ngôn ngữ định kiểu yếu hay động. Điều đó nghĩa là không cần phải khai báo kiểu của các biến trước khi dùng. Kiểu sẽ được xác định tự động trong khi chương trình được thực thi. Điều đó cũng có nghĩa là một biến có thể chứa giá trị của các kiểu dữ liệu khác nhau:

var foo = 42;    // foo là một số
var foo = "bar"; // foo là một chuỗi
var foo = true;  // foo là một boolean

Kiểu dữ liệu

Tiêu chuẩn ECMAScript mới nhất xác định bảy kiểu dữ liệu:

Giá trị nguyên thủy

Tất cả các kiểu trừ đối tượng đều được xác định giá trị bất biến (giá trị, không có khả năng thay đổi). Ví dụ và không giống C, một chuỗi là bất biến. Ta gọi chúng là "giá trị nguyên thủy" ("primitive").

Kiểu boolean

Kiểu boolean đại diện có hai giá trị logic: true, và false.

Kiểu null

Có duy nhất một giá trị: null. Xem null và Null để biết thêm chi tiết.

Kiểu undefined

Một biến chưa được gán giá trị có giá trị undefined. Xem undefined và Undefined để biết thêm chi tiết.

Kiểu số

Theo tiêu chuẩn ECMAScript, chỉ có duy nhất một kiểu số: the double-precision 64-bit binary format IEEE 754 value (có giá trị từ -(253 -1) đến 253 -1). Không có kiểu số nguyên. Ngoài việc có thể chứa giá trị dấu phẩy động, kiểu số có ba giá trị biểu tượng: +Infinity, -Infinity, and NaN (not-a-number).

Để kiểm tra lớn hơn hay nhỏ hơn +/-Infinity, bạn có thể xem Number.MAX_VALUE hoặc Number.MIN_VALUE và bất đầu từ ECMAScript 6, bạn cũng có thể kiểm tra một số có nằm trong khoảng double-precision floating-point bằng cách dùng Number.isSafeInteger() cũng như Number.MAX_SAFE_INTEGER và Number.MIN_SAFE_INTEGER. Ngoài phạm vi này, một số trong Javascript không còn an toàn nữa.

Có một số nguyên duy nhất có hai đại diện: 0 được đại diện bởi -0 và +0. ("0" là một bí danh của +0). Trong thực tế, điều này hầu như không có tác động. Ví dụ +0 === -0 là true. Tuy nhiên, có thể nhân thấy điều này khi chia một số cho không:

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

Mặc dù một số thường chỉ đại diện cho giá trị của nó, JavaScript cung cấp một vài toán tử nhị phân. Chúng có thể được sử dụng như một chuỗi boolean bằng cách dùng bit masking. Điều này thường được xem như là một cách tệ, tuy nhiên, JavaScript không cung cấp bất kỳ phương tiện nào khác để trình bày một tập hợp các boolean (như một mảng các boolean hay một đối tượng với các thuộc tính boolean). Bit masking cũng có xu hướng làm mã khó đọc, hiểu, và duy trì hơn. Nó có thể cấn thiết trong một môi trường rất hạn chế, giống như khi cố gắng để đối phó với hạn chế lưu trữ lưu trữ cục bộ hoặc trong trường hợp nặng khi mỗi chút so với đếm mạng. Kỹ thuật này chỉ nên được xem xét khi nó là biện pháp cuối cùng có thể được thực hiện để tối ưu hóa kích thước.

Kiểu chuỗi

Kiểu chuỗi được dùng để biểu diễn dữ liệu dạng văn bản. Nó là một dãy "các phần tử" số nguyên 16-bit. Mỗi phần tử có một vị trí trong chuỗi. Phần tử đầu tiên có chỉ số 0, tiếp theo là 1, ... . Độ dài của chuỗi là số phần tử của nó.

Không giống với những ngôn ngữ như 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 are new to JavaScript in ECMAScript Edition 6. A Symbol is a unique and immutable primitive value and may be used as the key of an Object property (see below). In some programming languages, Symbols are called atoms. You can also compare them to named enumerations (enum) in C. For more details see Symbol and the Symbol object wrapper in 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 it easy to privately bind data to an object.

Structured data: JSON

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

More objects in the standard library

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

Determining types using the typeof operator

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

Specifications

Specification Status Comment
ECMAScript 1st Edition (ECMA-262) Standard Initial definition.
ECMAScript 5.1 (ECMA-262)
The definition of 'Types' in that specification.
Standard  
ECMAScript 2015 (6th Edition, ECMA-262)
The definition of 'ECMAScript Data Types and Values' in that specification.
Standard  

See also

Document Tags and Contributors

Contributors to this page: Khai96_
Last updated by: Khai96_,
Hide Sidebar