第 39 题:JS 数据类型有哪些?

数据类型

基本类型

String、Number、Boolean、Null、Undefined

引用类型

Object、Array、Function

判断数据类型的方式

1. 使用 typeof

typeof 'test'          // string
typeof 1880            // number
typeof true            // boolean
typeof null            // object
typeof undefined       // undefined
typeof {}              // object
typeof []              // object
typeof function() {}   // function

缺点:判断基本类型还是可以的,判断引用类型作用就没那么大了。无法校验数组、对象、Null

2. 使用 constructor

let xiaoming = 'text';
xiaoming.constructor   // String(){}

let xiaoming = 1880;
xiaoming.constructor   // Number(){}

let xiaoming = true;
xiaoming.constructor   // Boolean(){}

let xiaoming = null;
xiaoming.constructor   // 报错

let xiaoming = undefined;
xiaoming.constructor   // 报错

let xiaoming = {};
xiaoming.constructor   // Object(){}

let xiaoming = [];
xiaoming.constructor   // Array(){}

let xiaoming = function() {};
xiaoming.constructor   // Function(){}

缺点:无法校验 Null 和 Undefined

3. 使用 instanceof

function A() {}

function A1() {}

function B() {}

A1.prototype = new A(); // A1 继承 A

let xiaoming = new A1(); // 实例化

console.log(xiaoming instanceof A); // true
console.log(xiaoming instanceof A1); // true
console.log(xiaoming instanceof B); // false

缺点:只适用于判断对象属于什么类型,其他的都不太适用

4. 使用 Object.prototype.toString.call()

Object.prototype.toString.call('text');            // [object String]
Object.prototype.toString.call(1880);              // [object Number]
Object.prototype.toString.call(true);              // [object Boolean]
Object.prototype.toString.call(null);              // [object Null]
Object.prototype.toString.call(undefined);         // [object Undefined]
Object.prototype.toString.call({});                // [object Object]
Object.prototype.toString.call([]);                // [object Array]
Object.prototype.toString.call(function() {});     // [object Function]

目前比较准确的一种方式

文章的内容/灵感都从下方内容中借鉴

posted @ 2021-09-03 14:53  Noxus丶SJ  阅读(124)  评论(0编辑  收藏  举报