首页 > Web开发 > 详细

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

时间:2021-09-03 21:12:44      阅读:24      评论:0      收藏:0      [点我收藏+]

数据类型

基本类型

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]

目前比较准确的一种方式

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

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

原文:https://www.cnblogs.com/noxussj/p/15223082.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!