检测 JavaScript 的数据类型

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zjuwwj/article/details/60880568

## 1. typeof
检测基本数据类型时,typeof 操作符用起来非常得心应手;但如果是复杂数据类型,typeof 操作符就显得有些无能为力了。

操作数类型 结果
undefined undefined
布尔值 boolean
字符串 string
数值 number
对象或者null object
函数 function

代码测试:

var test;
console.log(typeof test);//undefined

var booleanTest = true;
console.log(typeof booleanTest);//boolean

var stringTest = "test";
console.log(typeof stringTest);//string

var numberTest = 123;
console.log(typeof numberTest);//number

var specialTest = null;
console.log(typeof specialTest);//Object
var objectTest = {name:"ranran",age:22};
console.log(typeof specialTest);//Object

var functionTest = function() {var s = "ranran";}
console.log(typeof functionTest);//Function

2. instanceof

根据规定,所有引用类型的值都是 Object 的实例,所以在检测一个引用类型值和 Object 构造函数时,instanceof 操作符始终返回 true 。当我们想知道一个值是什么类型的对象的时候,可以使用 instanceof 操作符 。如果使用 instanceof 操作符检测基本类型的值,则该操作符始终会返回 false ,因为基本类型不是对象。

测试代码:

var arrayTest = new Array();
arrayTest instanceof Array;//true

var expressionTest = /at/g;//匹配字符串中所有的“at”的实例
expressionTest instanceof RegExp;//true

function Person(){};
var p = new Person();
p instanceof Person;//true

var d = new Date(); 
d instanceof Date;//true

3. constructor

constructor 属性返回对创建此对象的数组函数的引用。

var test=new Array();

if (test.constructor==Array){
    document.write("This is an Array");
}

if (test.constructor==Boolean){
    document.write("This is a Boolean");
}

if (test.constructor==Date){
    document.write("This is a Date");
}

if (test.constructor==String){
    document.write("This is a String");
}

//输出  This is an Array

4. Object.prototype.toString.call()

使用 Object.prototype 上原生toString()方法判断数据类型,使用方法如下
Object.prototype.toString.call(value),但是 Object.prototype.toString() 本身是允许被修改的,使用该方法检测数据类型前,请确保该方法未被修改。

4.1 判断基本类型:

Object.prototype.toString.call(null);//[object Null]
Object.prototype.toString.call(undefined);//[object Undefined]
Object.prototype.toString.call("abc");//[object String]
Object.prototype.toString.call(123);//[object Number]
Object.prototype.toString.call(true);//[object Boolean]

4.2 判断原生引用类型

function fn() {console.log("test");}
Object.prototype.toString.call(fn);//[object Function]

var date = new Date();
Object.prototype.toString.call(date);//[object Date]

var arr= [1,2,3];
Object.prototype.toString.call(arr);//[object Array]

var reg= /at/g;//匹配字符串中所有的“at”的实例
Object.prototype.toString.call(reg);//[object RegExp]

var person = {name:"ranran",age:22};
Object.prototype.toString.call(person);//[object Object]
Object.prototype.toString.call(person).slice(8,-1);//截取字符串后结果为:Object

猜你喜欢

转载自blog.csdn.net/zjuwwj/article/details/60880568