JavaScript数据类型

233 阅读1分钟

数据类型

- 基本数据类型

Number,String,Boolean,Undefined,Null,Symbol

- 引用数据类型

Array,Function,Object

数据类型判断

- typeOf:主要用于判断数据是不是基本数据类型

`typeof a === 'undefined'`:a未定义

`typeof a === 'number'`: a是数值

`typeof a === 'string'`: a是字符串

`typeof a === 'bollean'`: a是布偶类型

`typeof a === 'function'`: a是函数方法

`typeof a === 'object'`: a是null,数组或者是对象

- instanceof:主要的目的是用来检测引用类型,判断Array和RegExp,无法准确判断Function

`[] instanceof Array`: true

`[] instanceof Object`: true

`{} instanceof Object`: true

`() => {} instanceof Object`: true

`() => {} instanceof Function`: true

`/\d/ instanceof RegExp`: true

`'' instanceof String`: false

`1 instacneof Number`: false

- Object.prototype.toString.call():是对象的一个原生原型扩展函数,用来精确的区分数据类型

```
const type = Object.prototype.toString

type.call(''): object String

type.call([]): object Array

type.call({}): object Object

type.call(false): object Boolean

type.call(null): object Null

type.call(undefined): object Undefined

type.call(function(){}): object Function

```

问题1:js如何判断数组和对象

1.a instanceof array

[] instanceof Array: true;

{} instanceof Array: false;

ps: 不能去判断是否为Object, 因为:[] instanceof Object: true;

2.typeof与isNaN结合判断

!!!数组的length属性是Number类型, 对象的length属性是Undefined类型

image.png

const a = [1,2,3];
const b = {a: 1, b: 2, c: 3};
typeof a && !isNaN(a.length): true
typeof b && !isNaN(b.length): false

3.Object.prototype.toString.call();

Object.prototype.toString.call(a): [object Array]
Object.prototype.toString.call(b): [object object]

4. Array.isArray();