js范例检测

在javascript中我们一般运用typeof()来检测变量的范例,但是在一些庞杂情况下typeof()就显得力不从心了,下面我们来说说typeof,constructortoString,运用这三个举行范例的检测.

typeof

  • typeof检测js中的基础范例照样能够的.

var num = 1;
typeof(num) // number
var str = 'hello';
typeof(str); // string
var bool = true;
typeof(bool); // boolean

关于undefinednull就比较特别了,

typeof(undefined); // undefined
typeof(null); // object

关于函数、数组

function  a(){};
typeof(a); // function
var arr = [];
typeof(arr); // object

关于下面的检测就比较杂沓了:

typeof new Boolean(true) === 'object';
typeof new Number(1) ==== 'object';
typeof new String("abc") === 'object';
typeof new Date() === 'object';

constructor

该函数用来检察对象的组织函数

var bool = true;
console.log(bool.constructor == Boolean);// true
var num = 1; 
console.log(num.constructor == Number); // true
var str = 'hello';
console.log(str.constructor == String); // true

这里须要注重的是:
关于 undefinednull ,不能够运用 construcor检测.

toString

运用toString检测,必需运用Object.prototype.toString(),
先来看看这个东东输出什么鬼:

console.log(Object.prototype.toString()); // [object Object]

那末怎样运用toString()来举行检测呢?这里运用 call()来转变this的指向,

var bool = true;
console.log(Object.prototype.toString.call(bool)); // [object Boolean]
var num = 1;
console.log(Object.prototype.toString.call(num)); // [object Number]
var str = 'hello';
console.log(Object.prototype.toString.call(str)); // [object String]
var arr = [];
console.log(Object.prototype.toString.call(arr)); // [object Array]
var a = undefined;
console.log(Object.prototype.toString.call(a)); // [object Undefined]
var b = null;
console.log(Object.prototype.toString.call(b)); // [object Null]

能够看出 运用Object.prototype.toString.call()来检测 是比较圆满的.引荐运用.

补充 instanceof

检测某个实例是不是在某个对象的原型链上 原型链__proto__,

var c = [];
console.log(c instanceof Object); //true
var d = 123;  // 这些 一般范例 并非对象
console.log(d instanceof Object); //false
var str = 'hello'; //  不是对象
console.log(str instanceof Object); //false
var num = new Number(123);
console.log(num instanceof Object);
    原文作者:sdbxpjzq
    原文地址: https://segmentfault.com/a/1190000004527228
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞