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

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ố

operand

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à

// This stands since the beginning of JavaScript
typeof null === "object";
2.
// This stands since the beginning of JavaScript
typeof null === "object";
3 được biểu diễn dưới dạng con trỏ null [
// This stands since the beginning of JavaScript
typeof null === "object";
4 trong hầu hết các nền tảng]. Do đó,
// This stands since the beginning of JavaScript
typeof null === "object";
3 có
// This stands since the beginning of JavaScript
typeof null === "object";
2 dưới dạng thẻ loại, do đó giá trị trả về typeof
// This stands since the beginning of JavaScript
typeof null === "object";
8. [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";
9.

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

const str = new String["String"];
const num = new Number[100];

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

const func = new Function[];

typeof func; // "function"
0 sẽ trả về những người không theo nguyên tắc [
// This stands since the beginning of JavaScript
typeof null === "object";
8 hoặc
const str = new String["String"];
const num = new Number[100];

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

const func = new Function[];

typeof func; // "function"
2]. Hầu hết các đối tượng trả về, với ngoại lệ đáng chú ý là
const str = new String["String"];
const num = new Number[100];

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

const func = new Function[];

typeof func; // "function"
3, 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 [

const str = new String["String"];
const num = new Number[100];

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

const func = new Function[];

typeof func; // "function"
5]. 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 luôn đượ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ề

const str = new String["String"];
const num = new Number[100];

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

const func = new Function[];

typeof func; // "function"
8 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 [

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

typeof someData + " Wisen"; // "number Wisen"
typeof [someData + " Wisen"]; // "string"
0
// Parentheses can be used for determining the data type of expressions.
const someData = 99;

typeof someData + " Wisen"; // "number Wisen"
typeof [someData + " Wisen"]; // "string"
1 và
// Parentheses can be used for determining the data type of expressions.
const someData = 99;

typeof someData + " Wisen"; // "number Wisen"
typeof [someData + " Wisen"]; // "string"
2] trong cùng một khối trước khi dòng khai báo sẽ ném
// Parentheses can be used for determining the data type of expressions.
const someData = 99;

typeof someData + " Wisen"; // "number Wisen"
typeof [someData + " Wisen"]; // "string"
3. 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

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

typeof someData + " Wisen"; // "number Wisen"
typeof [someData + " Wisen"]; // "string"
4 với loại
// Parentheses can be used for determining the data type of expressions.
const someData = 99;

typeof someData + " Wisen"; // "number Wisen"
typeof [someData + " Wisen"]; // "string"
5.

typeof document.all === "undefined";

Mặc dù

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

typeof someData + " Wisen"; // "number Wisen"
typeof [someData + " Wisen"]; // "string"
4 cũng giả mạo và lỏng lẻo bằng
// Parentheses can be used for determining the data type of expressions.
const someData = 99;

typeof someData + " Wisen"; // "number Wisen"
typeof [someData + " Wisen"]; // "string"
5, nhưng nó không phải là
// Parentheses can be used for determining the data type of expressions.
const someData = 99;

typeof someData + " Wisen"; // "number Wisen"
typeof [someData + " Wisen"]; // "string"
5. Trường hợp của
// Parentheses can be used for determining the data type of expressions.
const someData = 99;

typeof someData + " Wisen"; // "number Wisen"
typeof [someData + " Wisen"]; // "string"
4 có 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"
8 đượ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ụ,

typeof undeclaredVariable; // "undefined"
2 là
// This stands since the beginning of JavaScript
typeof null === "object";
8, cũng như
typeof undeclaredVariable; // "undefined"
4,
typeof undeclaredVariable; // "undefined"
5, 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

typeof undeclaredVariable; // "undefined"
6 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

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

typeof someData + " Wisen"; // "number Wisen"
typeof [someData + " Wisen"]; // "string"
3, hãy sử dụng
typeof undeclaredVariable; // "undefined"
9 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 có thể xác định loại tên biến JavaScript?

Trong JavaScript, toán tử loại được sử dụng để tìm loại biến, đối tượng hoặc phương thức.Toán tử typeof trả về một trong các loại sau: số, boolean, đối tượng, chuỗi, chức năng không xác định.the typeof operator is used to find the type of a variable, object, or method. The typeof operator returns one of the following types: number, boolean, object, string, undefined, function.

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.

Bài Viết Liên Quan

Chủ Đề