js基础--数据类型检测的相关知识

欢迎访问个人我的博客:http://www.xiaolongwu.cngit

前言

最近工做有点忙,好几天都没更新技术博客了。es6

周末起床打开有道云笔记,发现本身的博客todolist里躺了一堆只有名字的文件。github

话很少说,咱们开干,加油!数组

干货满满

今天,咱们一块儿学习一下js中的数据类型检测相关的知识,也顺便作个总结。框架

一、数据类型介绍

咱们都知道,在js中分为基本数据类型和复杂数据类型。函数

基本数据类型又包括 Sting Number Boolean Null Undefined ,还有一个es6新增的Symbol,咱们这先不说。学习

复杂数据类型只有一种,那就是Object。.net

咱们平时见到的数组Array、正则RegExp、时间对象Date、函数Function等都属于Object。prototype

二、如何判断基本数据类型

这点想必你们都知道,可是我仍是要在这里啰嗦一下。插件

判断基本数据类型咱们能够选择typeof来判断。

这里须要注意就是返回值,他的返回值为小写字母开头的字符串。

//字符串
typeof 'leon'  // 'sting'

//整数
typeof 22  // 'number'

//undefined
typeof undefined  // 'undefined'

//Boolean
typeof true  // 'boolean'

//Null
typeof null  // 'object' 这为何是object ?
// 由于null表示的是一个空指针,指针表示的是引用型数据,因此返回object

//Object
typeof [1,2.3]      //'object' 
typeof {a: 'ww'}    //'object' 
typeof new Date()   //'object' 

//function
typeof function(){}     //"function"

三、instanceof

instanceof是用来检测引用类型,检测是那种类型的实例。

他的返回值为Boolean值,真为true,不然为false。

不能检测null,会报错。

// 这种检测方式通常不经常使用
[1, 2] instanceof Array  //true

({a: 1}) instanceof Object  //true

(function(){}) instanceof Function  //true

四、Constructor

返回结果为构造器,也能够检测自定义类型;

可是不适用于null和undefined。

'leon'.constructor == String // true
(1234).constructor == Number // true
(true).constructor == Boolean // true
[1, 2].constructor == Array // true
({name:'leon'}).constructor == Object // true
(function(){}).constructor == Function // true

检测自定义类型

function Leon(){}
var leon = new Leon();
leon.constructor == Leon;  // true

五、Object.prototype.toString.call(obj)

这种方式是最权威的,也是不少框架插件中用到的方法,推荐使用;

Object.prototype.toString.call('leon'); //"[object String]"
Object.prototype.toString.call(1234);  //"[object Number]"
Object.prototype.toString.call(true); //"[object Boolean]"
Object.prototype.toString.call([1,2,3]); //"[object Array]"
Object.prototype.toString.call({name:'leon'}); //"[object Object]"
Object.prototype.toString.call(function(){}); //"[object Function]"
Object.prototype.toString.call(null); //"[object Null]"
Object.prototype.toString.call(undefined); //"[object Undefined]"

实际使用时,能够这么写

var test = Object.prototype.toString.call('leon');
if(test == "[object String]") {
    console.log('这是个字符串')
}

//固然咱们也能够选择用正则去判断第二个单词,从而获得数据的类型

github文章资源地址:js基础--数据类型检测的相关知识

个人CSDN博客地址:https://blog.csdn.net/wxl1555

若是您对个人博客内容有疑惑或质疑的地方,请在下方评论区留言,或邮件给我,共同窗习进步。

邮箱:wuxiaolong802@163.com

相关文章
相关标签/搜索