javascript 推断数据类型的几种要领

javascript 推断数据类型的几种要领
一、typeof 直接返回数据类型字段,然则没法推断数组、null、对象

typeof 1
"number"

typeof NaN
"number"

typeof "1"
"string"

typeof true
"boolean"

typeof undefined
"undefined"

typeof null
"object"

typeof []
"object"

typeof {}
"object"

个中 null, [], {}都返回 “object”

二、instanceof 推断某个实例是否是属于原型

// 组织函数
function Fruit(name, color) {
    this.name = name;
    this.color = color;
}
var apple = new Fruit("apple", "red");

// (apple != null)
apple instanceof Object  // true
apple instanceof Array   // false

三、运用 Object.prototype.toString.call()推断

call()要领能够转变this的指向,那末把Object.prototype.toString()要领指向差别的数据类型上面,返回差别的效果

Object.prototype.toString.call(1)
"[object Number]"

Object.prototype.toString.call(NaN);
"[object Number]"

Object.prototype.toString.call("1");
"[object String]"

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(function a() {});
"[object Function]"

Object.prototype.toString.call([]);
"[object Array]"

Object.prototype.toString.call({});
"[object Object]"

末了我们能够定义一个圆满的推断数据类型的要领 _typeof()

function _typeof(obj){
  var s = Object.prototype.toString.call(obj);
  return s.match(/\[object (.*?)\]/)[1].toLowerCase();
};


_typeof([12,3,343]);
"array"

_typeof({name: 'zxc', age: 18});
"object"

_typeof(1);
"number"

_typeof("1");
"string"

 _typeof(null);
"null"

_typeof(undefined);
"undefined"

_typeof(NaN);
"number"

_typeof(Date);
"function"

_typeof(new Date());
"date"

_typeof(new RegExp());
"regexp"
    原文作者:zxc19890923
    原文地址: https://segmentfault.com/a/1190000018160547
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞