Hướng dẫn how do you check what type a variable is in javascript? - làm thế nào để bạn kiểm tra loại biến là gì trong javascript?

Phương thức GetVartype (bên dưới) hoạt động cho hầu hết các biến. Kiểm tra fiddle này. Đầu tiên nó sử dụng loại rất nhanh cho các trường hợp kết quả đáng tin cậy. Sau đó, nó sử dụng một phương pháp ToString đắt tiền hơn cho các trường hợp khác. Cuối cùng, nếu nó đang xử lý một đối tượng được đặt tên (được trả về bởi Firefox cho các đối tượng như tài liệu.location), nó sẽ kiểm tra các đối tượng giống như mảng và báo cáo chúng dưới dạng mảng.getVarType method (below) works for almost all variables. Check out this fiddle. It first uses the very fast typeof for cases where the results are reliable. Then it uses a more expensive toString method for other cases. Finally, if it is dealing with a named object (as returned by Firefox for objects like document.location) it checks for Array-like objects and reports them as arrays.

So sánh, typeof là nghèo nàn đáng xấu hổ. Loại ([]) trả về 'đối tượng', typeof (new Number ()) trả về đối tượng. Nó cũng trả về 'đối tượng' cho nhiều biến số khác không (cho mục đích thực tế) đối tượng. Xem kết quả fiddle để so sánh.typeof is embarrassingly poor. typeof([]) returns 'object', typeof(new Number()) returns object. It also returns 'object' for many other variables that aren't (for practical purposes) objects. See the fiddle results for a comparison.

  // Begin public utility /getVarType/
  // Returns 'Function', 'Object', 'Array',
  // 'String', 'Number', 'Null', 'Boolean', or 'Undefined'
  //
  getVarType = (function () {
    var typeof_map = {
      'undefined' : 'Undefined',
      'boolean'   : 'Boolean',
      'number'    : 'Number',
      'string'    : 'String',
      'function'  : 'Function',

      'Undefined' : 'Undefined',
      'Null'      : 'Null',
      'Boolean'   : 'Boolean',
      'Number'    : 'Number',
      'String'    : 'String',
      'Function'  : 'Function',
      'Array'     : 'Array',
      'StyleSheetList' : 'Array'
    };

    return function( data ) {
      var type, type_str;

      if ( data === null      ) { return 'Null'; }
      if ( data === undefined ) { return 'Undefined'; }

      type     = typeof( data );
      type_str = typeof_map[ type ];

      if ( type_str ) { return type_str; }

      type = {}.toString.call( data ).slice( 8, -1 );
      return typeof_map[ type ]
        || ( data instanceof Array ? 'Array' :
        ( data.propertyIsEnumerable(0) && data.length !== undefined
          ? 'Array' : 'Object' )
        );
    };
  }());
  // End public utility /getVarType/

Chế độ thất bại duy nhất có thể xảy ra nếu bạn đang kiểm tra một mảng có tên trống (ví dụ: một đối tượng DOM có thể suy nghĩ trống bên cạnh styleSheetList). Nhưng trên có thể thêm những người đó vào type_of_map khi cần thiết.

Tôi hy vọng điều đó sẽ giúp!

Toán tử typeof trả về một chuỗi cho biết loại giá trị của toán hạng.typeof operator returns a string indicating the type of the operand's value.

Thử nó

Cú pháp

Thông số

// 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 [1, 2, 4] === "object";

typeof new Date() === "object";
typeof /regex/ === "object";

// 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";
0

Một biểu thức đại diện cho đối tượng hoặc nguyên thủy có loại sẽ được trả về.

Sự mô tả

Bảng sau đây tóm tắt các giá trị trả về có thể của typeof. Để biết thêm thông tin về các loại và nguyên thủy, hãy xem thêm trang cấu trúc dữ liệu JavaScript.

Danh sách các giá trị này là đầy đủ. Không có động cơ tuân thủ cụ thể nào được báo cáo để sản xuất (hoặc có các giá trị được sản xuất trong lịch sử) ngoài các giá trị được liệt kê. Trình thám hiểm Internet cũ là trình duyệt duy nhất được biết là thực hiện các giá trị trả về bổ sung, trước khi thông số kỹ thuật loại bỏ hành vi của các chuỗi được xác định theo thực hiện typeof cho các đối tượng kỳ lạ không chuẩn.

Ví dụ

Cách sử dụng cơ bản

// 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 [1, 2, 4] === "object";

typeof new Date() === "object";
typeof /regex/ === "object";

// 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";

Loại null

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

Trong lần thực hiện đầu tiên của JavaScript, các giá trị JavaScript được biểu diễn dưới dạng thẻ loại và giá trị. Thẻ loại cho các đối tượng là

// 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 [1, 2, 4] === "object";

typeof new Date() === "object";
typeof /regex/ === "object";

// 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";
3.
// 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 [1, 2, 4] === "object";

typeof new Date() === "object";
typeof /regex/ === "object";

// 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";
4 được biểu diễn dưới dạng con trỏ null (
// 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 [1, 2, 4] === "object";

typeof new Date() === "object";
typeof /regex/ === "object";

// 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";
5 trong hầu hết các nền tảng). Do đó,
// 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 [1, 2, 4] === "object";

typeof new Date() === "object";
typeof /regex/ === "object";

// 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";
4 có
// 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 [1, 2, 4] === "object";

typeof new Date() === "object";
typeof /regex/ === "object";

// 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";
3 dưới dạng thẻ loại, do đó giá trị trả về typeof
// 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 [1, 2, 4] === "object";

typeof new Date() === "object";
typeof /regex/ === "object";

// 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";
9. (tài liệu tham khảo)

Một bản sửa lỗi đã được đề xuất cho Ecmascript (thông qua chọn tham gia), nhưng đã bị từ chối. Nó sẽ dẫn đến

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

Sử dụng toán tử mới

Tất cả các hàm của hàm tạo được gọi với

// This stands since the beginning of JavaScript
typeof null === "object";
1 sẽ trả về những người không theo nguyên tắc (
// 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 [1, 2, 4] === "object";

typeof new Date() === "object";
typeof /regex/ === "object";

// 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";
9 hoặc
// This stands since the beginning of JavaScript
typeof null === "object";
3). Hầu hết các đối tượng trả về, với ngoại lệ đáng chú ý là
// This stands since the beginning of JavaScript
typeof null === "object";
4, trả về một hàm.

const str = new String("String");
const num = new Number(100);

typeof str; // "object"
typeof num; // "object"

const func = new Function();

typeof func; // "function"

Cần cho dấu ngoặc trong cú pháp

Toán tử typeof có ưu tiên cao hơn các toán tử nhị phân như Bổ sung (

// This stands since the beginning of JavaScript
typeof null === "object";
6). Do đó, dấu ngoặc đơn là cần thiết để đánh giá loại kết quả bổ sung.

// Parentheses can be used for determining the data type of expressions.
const someData = 99;

typeof someData + " Wisen"; // "number Wisen"
typeof (someData + " Wisen"); // "string"

Tương tác với các biến không được khai báo và không được công khai

typeof thường được đảm bảo trả lại một chuỗi cho bất kỳ toán hạng nào mà nó được cung cấp. Ngay cả với các định danh không được khai báo, typeof sẽ trả về

// This stands since the beginning of JavaScript
typeof null === "object";
9 thay vì ném lỗi.

typeof undeclaredVariable; // "undefined"

Tuy nhiên, sử dụng typeof trên các khai báo từ vựng (

const str = new String("String");
const num = new Number(100);

typeof str; // "object"
typeof num; // "object"

const func = new Function();

typeof func; // "function"
1
const str = new String("String");
const num = new Number(100);

typeof str; // "object"
typeof num; // "object"

const func = new Function();

typeof func; // "function"
2 và
const str = new String("String");
const num = new Number(100);

typeof str; // "object"
typeof num; // "object"

const func = new Function();

typeof func; // "function"
3) trong cùng một khối trước khi dòng khai báo sẽ ném
const str = new String("String");
const num = new Number(100);

typeof str; // "object"
typeof num; // "object"

const func = new Function();

typeof func; // "function"
4. Các biến phạm vi khối nằm trong vùng chết tạm thời từ khi bắt đầu khối cho đến khi khởi tạo được xử lý, trong đó nó sẽ gây ra lỗi nếu được truy cập.

typeof newLetVariable; // ReferenceError
typeof newConstVariable; // ReferenceError
typeof newClass; // ReferenceError

let newLetVariable;
const newConstVariable = "hello";
class newClass {}

Hành vi đặc biệt của tài liệu. Tất cả

Tất cả các trình duyệt hiện tại hiển thị một đối tượng máy chủ không chuẩn

const str = new String("String");
const num = new Number(100);

typeof str; // "object"
typeof num; // "object"

const func = new Function();

typeof func; // "function"
5 với loại
const str = new String("String");
const num = new Number(100);

typeof str; // "object"
typeof num; // "object"

const func = new Function();

typeof func; // "function"
6.

typeof document.all === "undefined";

Mặc dù

const str = new String("String");
const num = new Number(100);

typeof str; // "object"
typeof num; // "object"

const func = new Function();

typeof func; // "function"
5 cũng giả mạo và lỏng lẻo bằng
const str = new String("String");
const num = new Number(100);

typeof str; // "object"
typeof num; // "object"

const func = new Function();

typeof func; // "function"
6, nhưng nó không phải là
const str = new String("String");
const num = new Number(100);

typeof str; // "object"
typeof num; // "object"

const func = new Function();

typeof func; // "function"
6. Trường hợp của
const str = new String("String");
const num = new Number(100);

typeof str; // "object"
typeof num; // "object"

const func = new Function();

typeof func; // "function"
5 có loại
// This stands since the beginning of JavaScript
typeof null === "object";
9 được phân loại trong các tiêu chuẩn web là "vi phạm cố ý" của tiêu chuẩn ECMAScript ban đầu cho khả năng tương thích web.

Phương pháp tùy chỉnh có loại cụ thể hơn

typeof rất hữu ích, nhưng nó không linh hoạt như có thể được yêu cầu. Ví dụ,

// Parentheses can be used for determining the data type of expressions.
const someData = 99;

typeof someData + " Wisen"; // "number Wisen"
typeof (someData + " Wisen"); // "string"
3 là
// 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 [1, 2, 4] === "object";

typeof new Date() === "object";
typeof /regex/ === "object";

// 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";
9, cũng như
// Parentheses can be used for determining the data type of expressions.
const someData = 99;

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

typeof someData + " Wisen"; // "number Wisen"
typeof (someData + " Wisen"); // "string"
6, v.v.

Để biết độ đặc hiệu cao hơn trong các loại kiểm tra, ở đây chúng tôi trình bày hàm

// Parentheses can be used for determining the data type of expressions.
const someData = 99;

typeof someData + " Wisen"; // "number Wisen"
typeof (someData + " Wisen"); // "string"
7 tùy chỉnh, chủ yếu bắt chước hành vi của typeof, nhưng đối với các đối tượng và chức năng không chính đáng (nghĩa là nó sẽ trả về một tên loại chi tiết hơn có thể.

function type(value) {
  if (value === null) {
    return "null";
  }
  const baseType = typeof value;
  // Primitive types
  if (!["object", "function"].includes(baseType)) {
    return baseType;
  }

  // Symbol.toStringTag often specifies the "display name" of the
  // object's class. It's used in Object.prototype.toString().
  const tag = value[Symbol.toStringTag];
  if (typeof tag === "string") {
    return tag;
  }

  // If it's a function whose source code starts with the "class" keyword
  if (
    baseType === "function" &&
    Function.prototype.toString.call(value).startsWith("class")
  ) {
    return "class";
  }

  // The name of the constructor; for example `Array`, `GeneratorFunction`,
  // `Number`, `String`, `Boolean` or `MyCustomClass`
  const className = value.constructor.name;
  if (typeof className === "string" && className !== "") {
    return className;
  }

  // At this point there's no robust way to get the type of value,
  // so we use the base implementation.
  return baseType;
}

Để kiểm tra các biến có khả năng không tồn tại mà nếu không sẽ ném

const str = new String("String");
const num = new Number(100);

typeof str; // "object"
typeof num; // "object"

const func = new Function();

typeof func; // "function"
4, hãy sử dụng
typeof undeclaredVariable; // "undefined"
0 vì hành vi này không thể được bắt chước với mã tùy chỉnh.

Thông số kỹ thuật

Sự chỉ rõ
Đặc tả ngôn ngữ Ecmascript # Sec-TypeOf-Coperator
# sec-typeof-operator

Tính tương thích của trình duyệt web

Bảng BCD chỉ tải trong trình duyệt

Xem thêm

Làm thế nào để bạn kiểm tra loại một biến A là gì?

Để có được loại biến trong Python, bạn có thể sử dụng hàm loại tích hợp (). Trong Python, mọi thứ đều là một đối tượng. Vì vậy, khi bạn sử dụng hàm loại () để in loại giá trị được lưu trữ trong một biến cho bàn điều khiển, nó sẽ trả về loại lớp của đối tượng.use the built-in type() function. In Python, everything is an object. So, when you use the type() function to print the type of the value stored in a variable to the console, it returns the class type of the object.

JavaScript có kiểm tra loại không?

Kiểm tra loại JavaScript không nghiêm ngặt như các ngôn ngữ lập trình khác.Sử dụng toán tử loại để phát hiện các loại.Có hai biến thể của cú pháp toán tử loại: typeof và typeof (biểu thức).Kết quả của một toán tử loại có thể gây hiểu lầm đôi khi.. Use the typeof operator for detecting types. There are two variants of the typeof operator syntax: typeof and typeof(expression) . The result of a typeof operator may be misleading at times.

Có biến có loại trong JavaScript?

JavaScript là các loại đầy đủ.TL; DR: Trong JavaScript, các biến không có loại, nhưng giá trị thì có.Mã trên hoàn toàn có giá trị vì trong JavaScript, các biến không có loại.Các biến có thể giữ các giá trị tùy ý và các giá trị này có loại.variables don't have types, but values do. The above code is perfectly valid because in JavaScript, variables don't have types. Variables can hold arbitrary values, and these values have types.

Một loại biến trong JavaScript là gì?

Trong JavaScript, một biến có thể chứa bất kỳ loại dữ liệu nào, chẳng hạn như chuỗi, boolean đúng hoặc sai, một đối tượng hoặc một số.Trước khi đặc tả ES6 được phát hành, có một cách để khai báo một biến trong JavaScript: Var.any types of data, such as a string, a true or false boolean, an object, or a number. Before the ES6 specification was released, there was one way to declare a variable in JavaScript: var.