js中如何判断一个值的类型

在js中我们有三种方法来帮助我们判断一个值的类型。

typeof运算符

console.log(typeof  123);   //number
console.log(typeof  '123');  //string
console.log(typeof  true);   //boolean
console.log(typeof  undefined);  //undefined
console.log(typeof  null);  //object
console.log(typeof  []);   //object
console.log(typeof  {});  //object
console.log(typeof  new Date());  //object
console.log(typeof  /\d/);  //object
console.log(typeof  function() {}); //function

我们从以上结果可以看出typeof的不足之处,它对于数值、字符串、布尔值分别返回numberstringboolean,函数返回functionundefined返回undefined,除此以外,其他情况都返回object
所以如果返回值为object,我们是无法得知值的类型到底是数组还是对象或者其他值。为了准确得到每个值的类型,我们必须使用js中另一个运算符instanceof。下面简单的说一下instanceof的用法。


instanceof运算符

instanceof运算符返回一个布尔值,表示指定对象是否为某个构造函数的实例。
instanceof运算符的左边是实例对象,右边是构造函数。它会检查右边构造函数的ptototype属性,是否在左边对象的原型链上。

var b =  [];
b  instanceof Array  //true
b  instanceof Object  //true

注意,instanceof运算符只能用于对象,不适用原始类型的值。


所以我们可以结合typeofinstanceof运算符的特性,来对一个值的类型做出较为准确的判断。

//得到一个值的类型
function getValueType(value) {
    var type = '';
    if (typeof value != 'object') {
        type = typeof value;
    } else {
        if (value instanceof Array) {
            type = 'array';
        } else {
            if (value instanceof Object) {
                type = 'object';
            } else {
                type = 'null';
            }
        }
    }
    return type;
}

getValueType(123);    //number
getValueType('123');  //string
getValueType(true);   //boolean
getValueType(undefined); //undefined
getValueType(null);  //null
getValueType([]);     //array
getValueType({});    //object
getValueType(function(){});  //function


Object.prototype.toString方法

console.log(Object.prototype.toString.call(2))        //[object Number]
console.log(Object.prototype.toString.call("123"))   //[object String]
console.log(Object.prototype.toString.call(true))    //[object Boolean]
console.log(Object.prototype.toString.call(null))     //[object Null]
console.log(Object.prototype.toString.call(undefined))   //[object Undefined]
console.log(Object.prototype.toString.call({}))       //[object Object]
console.log(Object.prototype.toString.call([]))         //[object Array]
console.log(Object.prototype.toString.call(/\d/i))     //[object RegExp]
console.log(Object.prototype.toString.call(Math))   //[object Math]
console.log(Object.prototype.toString.call(new Date()))  //[object Date]
console.log(Object.prototype.toString.call(function f() {}))  //[object Function]
console.log(Object.prototype.toString.call(new Error()))    //[object Error]

利用以上特性,我们可以写出一个更为准确的判断类型的方法。

function getValueType(value) {
  var type = Object.prototype.toString.call(value)
  type = type.slice(8, -1)
  return type
}

console.log(getValueType(2))     //Number
console.log(getValueType("123"))  //String
console.log(getValueType(true))   //Boolean
console.log(getValueType(null))   //Null
console.log(getValueType(undefined))   //Undefined
console.log(getValueType({}))    //Object
console.log(getValueType([]))    //Array
console.log(getValueType(/\d/i))   //RegExp
console.log(getValueType(Math))   //Math
console.log(getValueType(new Date()))   //Date
console.log(getValueType(function f() {}))    //Function
console.log(getValueType(new Error()))    //Error

这种方法判断无疑更为准确,而且简单。


欢迎大家的指正,共同学习进步,谢谢。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 第5章 引用类型(返回首页) 本章内容 使用对象 创建并操作数组 理解基本的JavaScript类型 使用基本类型...
    大学一百阅读 3,272评论 0 4
  • 1、JavaScript 定义了几种数据类型? 哪些是原始类型?哪些是复杂类型?原始类型(或基本数据类型)和复杂类...
    徐国军_plus阅读 506评论 0 1
  • 转载请声明出处 博客原文 随手翻阅以前的学习笔记,顺便整理一下放在这里,方便自己复习,也希望你有也有帮助吧 第一课...
    前端进阶之旅阅读 12,801评论 13 94
  • 不知道是否有人和我一样,总觉得生活不是那么真实,总觉得生活的剧本早已经写好,而我们不过是冥冥之中按照它的剧本进行...
    鹿维晴阅读 328评论 0 0
  • 1、死亡之下的罪恶 连夜读完东野圭吾的《濒死之眼》,被其惊悚罪恶深深震撼。在死亡的无可奈何之下,隐藏着人性的自私与...
    这只猫有点敏感阅读 45,977评论 9 7