0%

javascript data types

JavaScript Data Types

JavaScript是一种弱类型语言,它有八种数据类型,分别是:

  • String
  • Number
  • BigInt
  • Boolean
  • Null
  • Undefined
  • Symbol
  • Object

除了Object之外,其他的数据类型都是原始类型(Primitive types)。
注意:JavaScript中的Array、Function、Set、Map、RegExp等等都是Object类型。

如何判断一个变量的类型

在JavaScript中,我们可以使用typeof操作符来判断一个变量的类型。typeof操作符返回一个字符串,表示变量的类型。

1
2
3
4
5
6
7
8
9
typeof 'Hello'; // string
typeof 123; // number
typeof true; // boolean
typeof null; // object
typeof undefined; // undefined
typeof Symbol('Hello'); // symbol
typeof {}; // object
typeof []; // object
typeof function(){}; // function

注意:虽然Function类型是Object的子类型,但是typeof操作符返回的是function

如何精准的判断一个变量的类型

在JavaScript中,我们可以使用Object.prototype.toString方法来精准的判断一个变量的类型。

1
2
3
4
5
Object.prototype.toString.call('Hello'); // [object String]
Object.prototype.toString.call(123); // [object Number]
Object.prototype.toString.call(true); // [object Boolean]
Object.prototype.toString.call(null); // [object Null]
Object.prototype.toString.call([]); // [object Array]

注意:Object.prototype.toString方法返回的是一个字符串,表示变量的类型。所以我们可以封装一个函数来判断一个变量的类型。(注意:判断数组可以用更好的方法 - Array.isArray方法)

1
2
3
function getType(value) {
return Object.prototype.toString.call(value).slice(8, -1);
}

以下几个需要注意:

1
2
3
4
5
6
typeof typeof 1; // string, typeof 永远返回字符串。
typeof null; // object, 这是一个历史遗留问题。看这里:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof#typeof_null
typeof NaN; // number, NaN是一个特殊的number类型。
typeof class C {}; // function, class是一个语法糖,本质上还是function。
typeof something; // undefined, 如果变量没有声明,那么typeof返回undefined。不会报错。
typeof document.all; // undefined, All current browsers expose a non-standard host object document.all with type undefined

instanceof 操作符

instanceof操作符用来判断一个对象是否是某个构造函数的实例。

1
2
3
const arr = [1, 2, 3];
arr instanceof Array; // true
arr instanceof Object; // true

References: