js基本--数据类型检测的相干学问

迎接接见我的个人博客:http://www.xiaolongwu.cn

媒介

近来事情有点忙,好几天都没更新手艺博客了。

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

话不多说,我们开干,加油!

干货满满

本日,我们一同进修一下js中的数据范例检测相干的学问,也趁便做个总结。

1、数据范例引见

我们都晓得,在js中分为基本数据范例和庞杂数据范例。

基本数据范例又包含 Sting Number Boolean Null Undefined ,另有一个es6新增的Symbol,我们这先不说。

庞杂数据范例只要一种,那就是Object。

我们日常平凡见到的数组Array、正则RegExp、时候对象Date、函数Function等都属于Object。

2、怎样推断基本数据范例

这点想必人人都晓得,然则我照样要在这里烦琐一下。

推断基本数据范例我们能够挑选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"

3、instanceof

instanceof是用来检测援用范例,检测是那种范例的实例。

他的返回值为Boolean值,真为true,否则为false。

不能检测null,会报错。

// 这类检测体式格局平常不经常运用
[1, 2] instanceof Array  //true

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

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

4、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 

5、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

    原文作者:LeonWuV
    原文地址: https://segmentfault.com/a/1190000018458270
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞