Переклад не закінчено. Будь ласка, допоможіть перекласти цю статтю з англійської.
Оператор typeof повертає строку, яка вказує на тип невичесленого операнда.
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.
Синтакс
Оператор typeof супроводжується його операндом:
typeof operand typeof(operand)
Параметри
operand- Вираз, що представляє об'єкт або primitive}, тип якого потрібно повернути.
Опис
Наступна таблиця підсумовує можливі повернені значення typeof. Для отримання додаткової інформації про типи та примітиви див. також сторінку структури даних JavaScript data structure.
| Type | Result |
|---|---|
| Undefined | "undefined" |
| Null | "object" (see below) |
| Boolean | "boolean" |
| Number | "number" |
| BigInt | "bigint" |
| String | "string" |
| Symbol (new in ECMAScript 2015) | "symbol" |
| Host object (provided by the JS environment) | Залежно від реалізації |
| Function object (implements [[Call]] in ECMA-262 terms) | "function" |
| Any other object | "object" |
Приклади
// Numbers
typeof 37 === 'number';
typeof 3.14 === 'number';
typeof(42) === 'number';
typeof Math.LN2 === 'number';
typeof Infinity === 'number';
typeof NaN === 'number'; // Незважаючи на "Not-A-Number"
typeof Number('1') === 'number'; // Number намагається розібрати речі на числа
typeof 42n === 'bigint';
// Strings
typeof '' === 'string';
typeof 'bla' === 'string';
typeof `template literal` === 'string';
typeof '1' === 'string'; // зауважте, що number у string все ще є typeof string
typeof (typeof 1) === 'string'; // typeof завжди повертає string
typeof String(1) === 'string'; // String перетворює що-небудь у рядок, безпечніше, ніж toString
// Booleans
typeof true === 'boolean';
typeof false === 'boolean';
typeof Boolean(1) === 'boolean'; // Boolean() буде перетворювати значення на основі, якщо вони є правдивими або хибними
typeof !!(1) === 'boolean'; // два написання ! (logical NOT) оператора є рівні до 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';
// використовуй Array.isArray або Object.prototype.toString.call
// щоб відрізняти регулярні об'єкти від масивів
typeof [1, 2, 4] === 'object';
typeof new Date() === 'object';
typeof /regex/ === 'object'; // про Regular expressions секцію можна глянути в historical results
// Нижче заплутані, небезпечні та марнотратні. Уникайте їх.
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) The definition of 'The typeof Operator' in that specification. |
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
| Desktop | Mobile | Server | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
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 |
Legend
- Full support
- Full support
IE-specific notes
On IE 6, 7, and 8 a lot of host objects are objects and not functions. For example:
typeof alert === 'object'