数据类型

ECMAScript 标准定义了 8 种数据类型:

7 种原始类型 和 Object

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

使用 typeof 操作符判断对象类型

console.log(typeof 42);
// expected output: "number"
类型结果
Undefined"undefined"
Null"object"
Boolean"boolean"
Number"number"
BigInt(ECMAScript 2020 新增)"bigint"
String"string"
Symbol (ECMAScript 2015 新增)"symbol"
Function 对象 (按照 ECMA-262 规范实现 [[Call]])"function"
其他任何对象"object"

typeof 只能检测基本数据类型,包括 Boolean、Undefined、String、Number、Symbol,而 Null、Array、Object 检测出来都是 Object,无法检测具体是哪种引用类型。

如何判断数据类型是数组?

比如要检测一个变量/数据类型是否为数组 Array,使用 Array.isArray()

Array.isArray()

在编程环境运行的情况下,isArray 是最简单直接的检测是否为数组的有效方法

// 下面的函数调用都返回 true
Array.isArray([]);
Array.isArray([1]);
Array.isArray(new Array());
Array.isArray(new Array('a', 'b', 'c', 'd'))
// 鲜为人知的事实:其实 Array.prototype 也是一个数组。
Array.isArray(Array.prototype);

原型链检测对象类型

instanceof

instanceof 运算符用来检测对象的构造函数 constructor.prototype 是否出现在某个实例对象的原型链上。

[] instanceof Array
//true

new Object() instanceof Object
//true

'a' instanceof String; //false
//false

不建议使用 instanceof 检测 String 类型数据,String 对象和 Date 对象都属于 Object 类型,他们是由 Object 类派生出来的。

Object.prototype.toString.call()

对于检测数据,被检测对象必定会存在 toString 方法,如果 toString 方法没有重写的话,会返回 [object type],其中 type 为对象的类型。

// only implement if no native implementation is available
if (typeof Array.isArray === 'undefined') {
  Array.isArray = function(obj) {
    return Object.prototype.toString.call(obj) === '[object Array]';
  }
}

undefined 和 null 的区别

一个已定义但没有被赋值的变量,或函数如果没有使用 return 语句指定返回值,就会返回一个undefined值。

null 是 JavaScript 7 种原始类型之一。null 是表示缺少的标识,指示变量未指向任何对象。

typeof null        // "object" (因为一些以前的原因而不是'null')
typeof undefined   // "undefined"
null === undefined // false
null  == undefined // true 因为undefined派生自null
null === null // true
null == null // true
!null //true
isNaN(1 + null) // false
isNaN(1 + undefined) // true

参考

JavaScript 数据类型和数据结构

Array.isArray() - MDN

typeof - MDN

instanceof - MDN

Object.prototype.toString()

undefined

null

How to check if an object is an array?

Determining with absolute accuracy whether or not a JavaScript object is an array

标签: none

添加新评论