Решение... Советы... Windows 10

«Сложно о простом». Типы данных JS. В поисках истины примитивов и объектов. Типы данных Javascript Js узнать тип переменной

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

Dynamic typing

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

Var foo = 42; // foo is now a number foo = "bar"; // foo is now a string foo = true; // foo is now a boolean

Data types

The latest ECMAScript standard defines eight data types:

  • Seven data types that are :

Primitive values

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

Boolean type

Boolean represents a logical entity and can have two values: true , and false . See Boolean and Boolean for more details.

Null type

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
[] Any JavaScript type The value retrieved by a get access of the property. undefined
[] Boolean If false , the property"s [] can"t be changed. false
[] Boolean for...in loops. See also Enumerability and ownership of properties false
[] Boolean If false , the property can"t be deleted, can"t be changed to an accessor property and attributes other than [] and [] can"t be changed. false
Obsolete attributes (as of ECMAScript 3, renamed in ECMAScript 5)
Attribute Type Description
Read-only Boolean Reversed state of the ES5 [] attribute.
DontEnum Boolean Reversed state of the ES5 [] attribute.
DontDelete Boolean Reversed state of the ES5 [] attribute.

Accessor property

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

Attributes of an accessor property
Attribute Type Description Default value
[] 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
[] 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
[] Boolean If true , the property will be enumerated in for...in loops. false
[] Boolean If false , the property can"t be deleted and can"t be changed to a data property. false

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

"Normal" objects, and functions

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

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

Dates

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

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 2015 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 Value Range Size in bytes Description Web IDL type Equivalent C type
Int8Array -128 to 127 1 8-bit two"s complement signed integer byte int8_t
Uint8Array 0 to 255 1 8-bit unsigned integer octet uint8_t
Uint8ClampedArray 0 to 255 1 8-bit unsigned integer (clamped) octet uint8_t
Int16Array -32768 to 32767 2 16-bit two"s complement signed integer short int16_t
Uint16Array 0 to 65535 2 16-bit unsigned integer unsigned short uint16_t
Int32Array -2147483648 to 2147483647 4 32-bit two"s complement signed integer long int32_t
Uint32Array 0 to 4294967295 4 32-bit unsigned integer unsigned long uint32_t
Float32Array 1.2x10 -38 to 3.4x10 38 4 32-bit IEEE floating point number (7 significant digits e.g. 1.1234567) unrestricted float float
Float64Array 5.0x10 -324 to 1.8x10 308 8 64-bit IEEE floating point number (16 significant digits e.g. 1.123...15) unrestricted double double
BigInt64Array -2 63 to 2 63 -1 8 64-bit two"s complement signed integer bigint int64_t (signed long long)
BigUint64Array 0 to 2 64 -1 8 64-bit unsigned integer bigint uint64_t (unsigned long long)

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 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)
Standard Added Symbol.
ECMAScript Latest Draft (ECMA-262)
The definition of "ECMAScript Data Types and Values" in that specification.
Draft

В процессе работы компьютерные программы манипулируют значениями, такими как число 7 или текст "HelloWorld!". Каждое значение, которое может быть представлено и обработано в языке программирования относится к определённому типу данных . Тип данных определяет типы значений, которые используются в языке программирования.

В JavaScript типы данных можно разделить на две категории: простые (их также называют примитивными ) типы и составные (их также называют ссылочными или объекты ).

  • string - текстовые строки (обычно их называют просто - строки)
  • number - числа
  • boolean - логические (булевы) значения

Так же к простым типам относятся два специальных значения:

  • null
  • undefined

К составным типам данных относятся:

  • function - функции
  • array - массивы
  • object - объекты

Разница между простыми и составными типами

Разница между простыми и составными типами проявляется при копировании значений.

Когда переменной (параметру функции, свойству или элементу массива) присваивается значение простого типа, например число, то в переменную записывается само значение (в данном случае - число). При выполнении присваивания одной переменной (со значением простого типа) другой переменной происходит копирование значения. В результате каждая переменная имеет свою копию значения и изменения в одной из переменных никак не сказывается на значении другой:

Var num1 = 10; var num2 = num1; // Копируем значение alert("num1: " + num1 + // 10 "\nnum2: " + num2); // 10 num1 = 15; // Изменяем значение alert("num1: " + num1 + // 15 "\nnum2: " + num2); // 10

Когда переменной (параметру функции, свойству или элементу массива) присваивается значение составного типа, например объект, то в переменную записывается ссылка на значение (в данном случае - ссылка на объект). При выполнении присваивания одной переменной (в значении которой ссылка на составное значение) другой переменной происходит копирование ссылки на составное значение. В результате обе переменные ссылаются на одно и то же составное значение и любые внесённые изменения в значении одной из переменных будут сказываться на другой переменной:

Var o1 = {x:10}; var o2 = o1; // Копируем ссылку на объект alert("o1.x: " + o1.x + // 10 "\no2.x: " + o2.x); // 10 o2.x = 15; // Изменяем значение alert("o1.x: " + o1.x + // 15 "\no2.x: " + o2.x); // 15

null и undefined

Тип null имеет всего одно значение - null . Значение null является ссылкой на пустой объект и имеет специальное назначение - обычно оно используется для инициализации переменной, которой впоследствии будет присвоен объект.

Тип undefined имеет всего одно значение - undefined . Значение undefined указывает на изначальное отсутствие какого-либо значения. Получить значение undefined можно следующим образом:

  • При обращении к переменной, которая была объявлена, но не была инициализирована.
  • При обращении к несуществующему свойству объекта.
  • При обращении к несуществующему элементу массива.
  • При обращении к параметрам функции, которые не были инициализированы аргументами при вызове функции.
  • Возвращается функциями, которые не имеют возвращаемого значения.
  • Возвращается оператором typeof, если операндом является несуществующая переменная.
var bar; document.write(bar); Попробовать »

Идентификатор undefined является именем предопределённой глобальной переменной, которая инициализирована значением undefined . Переменная undefined доступна только для чтения.

Объекты обёртки

Каждый раз, когда в программе предпринимается попытка обратиться к свойству или методу значения примитивного типа, интерпретатор временно преобразует примитивное значение в объект соответствующего типа. Временные объекты, в которые преобразуются значения примитивного типа, называют объектами обёртками . Эти объекты используются интерпретатором для доступа к нужному свойству или методу. Сразу после обращения к свойству или методу объект обёртка уничтожается. Объекты обёртки создаются только для значений типа number , string и boolean . Значения null и undefined не имеют объектов оберток: любые попытки обратиться к свойствам этих значений будут вызывать ошибку.

Если для объекта обёртки попытаться установить новое свойство то, новое свойство не будет сохранено, так как объект обёртка уничтожается сразу после того, как выполнит свою работу:

Var str = "текст"; str.len = 5; // Установить свойство со значением. Сразу после этого объект уничтожается alert(str.len); // undefined, так как предыдущий объект обёртка уже уничтожен

Объекты обёртки можно рассматривать просто как реализацию удобства для работы со значениями примитивного типа и вообще не думать о них.

Урок №3
Типы данных в языке JavaScript

В прошлом уроке мы выяснили, что переменная — это именованная область памяти, которая хранит в себе какие-либо данные (значения).

У каждого значения в JavaScript, имеется свой тип данных . Всего в JavaScript существует 6 типов данных, в этом уроке по JavaScript, мы рассмотрим 4 типа данных:
— числовой тип данных number ,
— строковый тип данных string ,
— логический тип данных boolean ,
— неопределённый тип данных undefined .

Остальные два изучим чуть позже:
— объектный тип данных object
— пустой тип данных null

Оператор typeof

Прежде чем рассмотреть типы данных JavaScript , познакомимся сначала с оператором typeof , он позволяет узнать какой тип данных присвоен переменной, делается это следующим образом:

Alert(typeof имяПеременной);

После этого скрипт должен выдать какое-либо сообщение: number , string , boolean , undefined , object .

Тип данных: число (number)

Когда переменной, в качестве значения, присваивается какое-либо число (без кавычек) , её тип данных становится number

Var myNumber; myNumber = 5; alert(typeof myNumber);

В первой строке мы создали переменную с именем myNumber , во второй строке, присвоили переменной значение 5 , в третьей с помощью оператора typeof вычислили тип данных у переменной myNumber , а функция alert() показала нам результат этих вычислений.

В итоге, данный скрипт выведет нам сообщение number . Если число обрамить кавычками (одинарными "5" или двойными "5" ) , то оно превратится в строку string .

Тип данных: строка (string)

Когда переменной в качестве значения присваивается какое-либо значение, заключённое в двойные " " или одинарные кавычки " " , то её тип данных становится string .

Var myString; myString = "Привет, я строка JavaScript!"; alert(typeof myString);

В первой строке мы создали переменную с именем myString , во второй строке, присвоили переменной значение "Привет, я строка JavaScript!" , в третьей с помощью оператора typeof вычислили тип данных у переменной myString , а функция alert() показала нам результат этих вычислений. В итоге, данный скрипт должен вывести нам сообщение string .

Тип данных: логический тип данных (boolean)

Когда переменной в качестве значения присваивается true или false , без кавычек , то её тип данных становится boolean .

Тип данных boolean — это логический тип данных, он имеет всего два значения: true (правда) или false (ложь) .

Var myBoolean; myBoolean = true; alert(typeof myBoolean);

В первой строке мы создали переменную с именем myBoolean , во второй строке, присвоили переменной значение true , в третьей с помощью оператора typeof вычислили тип данных у переменной myBoolean , а функция alert() показала нам результат этих вычислений. В итоге, данный скрипт должен вывести нам сообщение boolean .

Логический тип данных, мы изучим более подробно в следующих уроках, посвящённых операциям сравнения, логическим операциям и оператору ветвления if

Тип данных: undefined

Тип данных undefined появляется тогда, когда переменная объявлена, но не инициализирована, т.е. переменная создана, но значения ей не присвоили.

Var myUndefined; alert(typeof myUndefined);

В первой строке мы создали переменную с именем myUndefined , во второй строке с помощью оператора typeof вычислили тип данных у переменной myUndefined , а функция alert() показала нам результат этих вычислений. В итоге, данный скрипт должен вывести нам сообщение undefined .

Доступ к значению переменной

Чтобы получить доступ, к значению переменной, нужно обратиться к ней по имени:

// объявляем переменные var myString; var myNumber; // инициализируем переменные myString = "Привет, МИР!"; myNumber = 5; // обращаемся к переменным alert(myString); alert(myNumber);

В первой и второй строках кода мы создали переменные myString и myNumber , в третьей и четвёртой строках присвоили переменным значения "Привет, МИР!" и 5 , в пятой и шестой строках с помощью функции alert() вывели результаты Привет, МИР! и 5

Почти в любом языке программировании существуют различные типы переменных и JavaScript тут сюрпризов не преподносит. Как правило, это стандартный набор типов: целый (integer ), вещественный (double ), строковый (string ), булевский (boolean ) и массив (array ). Давайте разберём каждый тип переменной в JavaScript подробнее.

Во-первых, сразу заметим, что переменная любого типа начинается с ключевого слова "var ", и лишь значение переменной определяет тип переменной. Более того, тип переменной в JavaScript может быть изменён в любой точке программы.

Начнём с самого простого - целого типа, знакомого нам по предыдущей статье. Целый тип - это обычные целое число, например, -100, -34, 0, 15, 259 и так далее. Соответственно, целый тип создаётся с помощью присвоения переменной целого значения, например, так:

Var number = -323;

Следующий тип переменной - это вещественный тип, или, как принято его называть, double . Тип double - это вещественные числа, то есть абсолютно любые числа, кроме мнимых (если не знаете, что такое мнимые числа, то не обращайте на это внимание). Например, -3.4, -1.032, 35.599212, 0.0001. Так же как и с другими типами, для создания вещественной переменной необходимо инициализировать переменную одним из подобных значений. Вот пример:

Var number = 32.3291;

Обратите внимание, что целая часть от дробной отделяется не "запятой " (как принято у нас), а "точкой ".

Следующий тип переменной - это строковый. Строковый тип в JavaScript используется очень часто, не реже, чем другие, если не больше. Строковый тип - это какая-либо строка. Для примера такая: "string", "732", "My name"s Michael". Обратите внимание, что строка задаётся в кавычках. В частности, строка "732" отличается от числа 732. Создаётся строка аналогично другим типам в JavaScript :

Var str = "some string";

Ещё один тип переменной - это булевский. Тип этой переменной может содержать одно из двух значений: true (истина) или false (ложь). Переменная используется в условных операторах, о которых мы поговорим позднее. А пока пример создания булевской переменной:

Var bool = true;

И последний тип - это массив. Самый сложный тип из всех, однако, очень важный и присутствующий почти во всех языках программирования. Это тип, который содержит в себе несколько различных переменных, причём, возможно, что даже разных типов. Создаётся массив в JavaScript таким образом:

Var array = new Array(3, 7, 12, true, 4.5, "some string", true);

В примере создаётся массив из 7-ми значений, которые могут быть считаны или перезаписаны. Встаёт вопрос: как обратиться к элементу массива. Очень просто! Синтаксис обращения к элементу массива следующий: название_ массива[номер_элемента]. Обратите внимание, что нумерация в массиве начинается с "0 ". Поэтому элемент со значением "3 " - это элемент под номером "0 ". Для примера покажу, как можно вывести элемент массива в окно браузера и перезаписать его.

Document.write(array);
array = array + 1;
document.write(array);

Советую Вам выполнить этот скрипт, чтобы окончательно разобраться в массивах, ведь без этого типа переменной немыслимо программирование, даже на JavaScript .

Это все типы переменных в JavaScript .

The typeof operator returns a string indicating the type of the unevaluated operand.

The source for this interactive example is stored in a GitHub repository. If you"d like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.

Syntax

The typeof operator is followed by its operand:

Typeof operand typeof(operand )

Parameters

operand An expression representing the object or whose type is to be returned.

Description

The following table summarizes the possible return values of typeof . For more information about types and primitives, see also the JavaScript data structure page.

Type Result
"undefined"
Null "object" (see )
Boolean "boolean"
Number "number"
BigInt "bigint"
String "string"
Symbol (new in ECMAScript 2015) "symbol"
Host object (provided by the JS environment) Implementation-dependent
Function object (implements [] in ECMA-262 terms) "function"
Any other object "object"

Examples

// Numbers typeof 37 === "number"; typeof 3.14 === "number"; typeof(42) === "number"; typeof Math.LN2 === "number"; typeof Infinity === "number"; typeof NaN === "number"; // Despite being "Not-A-Number" typeof Number("1") === "number"; // Number tries to parse things into numbers typeof Number("shoe") === "number"; // including values that cannot be type coerced to a number typeof 42n === "bigint"; // Strings typeof "" === "string"; typeof "bla" === "string"; typeof `template literal` === "string"; typeof "1" === "string"; // note that a number within a string is still typeof string typeof (typeof 1) === "string"; // typeof always returns a string typeof String(1) === "string"; // String converts anything into a string, safer than toString // Booleans typeof true === "boolean"; typeof false === "boolean"; typeof Boolean(1) === "boolean"; // Boolean() will convert values based on if they"re truthy or falsy typeof !!(1) === "boolean"; // two calls of the ! (logical NOT) operator are equivalent to Boolean() // Symbols typeof Symbol() === "symbol" typeof Symbol("foo") === "symbol" typeof Symbol.iterator === "symbol" // Undefined typeof undefined === "undefined"; typeof declaredButUndefinedVariable === "undefined"; typeof undeclaredVariable === "undefined"; // Objects typeof {a: 1} === "object"; // use Array.isArray or Object.prototype.toString.call // to differentiate regular objects from arrays typeof === "object"; typeof new Date() === "object"; typeof /regex/ === "object"; // See Regular expressions section for historical results // The following are confusing, dangerous, and wasteful. Avoid them. typeof new Boolean(true) === "object"; typeof new Number(1) === "object"; typeof new String("abc") === "object"; // Functions typeof function() {} === "function"; typeof class C {} === "function"; typeof Math.sin === "function";

Additional information

null

// This stands since the beginning of JavaScript typeof null === "object";

In the first implementation of JavaScript, JavaScript values were represented as a type tag and a value. The type tag for objects was 0. null was represented as the NULL pointer (0x00 in most platforms). Consequently, null had 0 as type tag, hence the "object" typeof return value. (reference)

A fix was proposed for ECMAScript (via an opt-in), but was rejected . It would have resulted in typeof null === "null" .

Using new operator

// All constructor functions, with the exception of the Function constructor, will always be typeof "object" var str = new String("String"); var num = new Number(100); typeof str; // It will return "object" typeof num; // It will return "object" var func = new Function(); typeof func; // It will return "function"

Need for parentheses in Syntax

// Parentheses can be used for determining the data type of expressions. var iData = 99; typeof iData + " Wisen"; // "number Wisen" typeof (iData + " Wisen"); // "string"

Regular expressions

Callable regular expressions were a non-standard addition in some browsers.

Typeof /s/ === "function"; // Chrome 1-12 Non-conform to ECMAScript 5.1 typeof /s/ === "object"; // Firefox 5+ Conform to ECMAScript 5.1

Errors

Before ECMAScript 2015, typeof was always guaranteed to return a string for any operand it was supplied with. Even with undeclared identifiers, typeof will return "undefined" . Using typeof could never generate an error.

But with the addition of block-scoped let and Statements/const using typeof on let and const variables (or using typeof on a class) in a block before they are declared will throw a ReferenceError . Block scoped variables are in a "temporal dead zone " from the start of the block until the initialization is processed, during which, it will throw an error if accessed.

Typeof undeclaredVariable === "undefined"; typeof newLetVariable; // ReferenceError typeof newConstVariable; // ReferenceError typeof newClass; // ReferenceError let newLetVariable; const newConstVariable = "hello"; class newClass{};

Exceptions

All current browsers expose a non-standard host object document.all with type undefined .

Typeof document.all === "undefined";

Although the specification allows custom type tags for non-standard exotic objects, it requires those type tags to be different from the predefined ones. The case of document.all having type "undefined" is classified in the web standards as a "willful violation" of the original ECMA JavaScript standard.

Specifications

Specification Status Comment
ECMAScript Latest Draft (ECMA-262)
Draft
ECMAScript 2015 (6th Edition, ECMA-262)
The definition of "The typeof Operator" in that specification.
Standard
ECMAScript 5.1 (ECMA-262)
The definition of "The typeof Operator" in that specification.
Standard
ECMAScript 3rd Edition (ECMA-262)
The definition of "The typeof Operator" in that specification.
Standard
ECMAScript 1st Edition (ECMA-262)
The definition of "The typeof Operator" in that specification.
Standard Initial definition. Implemented in JavaScript 1.1.

Browser compatibility

The compatibility table on this page is generated from structured data. If you"d like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.

Update compatibility data on GitHub

Desktop Mobile Server
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet Node.js
typeof Chrome Full support Yes Edge Full support 12 Firefox Full support 1 IE Full support Yes Opera Full support Yes Safari Full support Yes WebView Android Full support Yes Chrome Android Full support Yes Firefox Android Full support 4 Opera Android Full support Yes Safari iOS Full support Yes Samsung Internet Android Full support Yes nodejs Full support Yes