为了账号安全,请及时绑定邮箱和手机立即绑定

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

标签:
Html5 CSS3 面试

数据类型

基本类型

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]

目前比较准确的一种方式

点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
Web前端工程师
手记
粉丝
6
获赞与收藏
12

关注作者,订阅最新文章

阅读免费教程

  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消