Javascript有5种简单数据类型和一种复杂数据类型
要检测一个变量是不是基本数据类型, typeof 操作符是最佳的工具。
var s = "Nicholas";var b = true;var i = 22;var u;var n = null;var o = new Object();alert(typeof s); //stringalert(typeof i); //numberalert(typeof b); //booleanalert(typeof u); //undefinedalert(typeof n); //objectalert(typeof o); //object
但是从上面的执行结果可以看到,如果变量的值是一个对象或 null,则 typeof 操作符会像例子中所示的那样返回"object" ,那么问题来了,如何检测Null呢? 如果想将null和对象区分开,则必须进行显示检查
function getType(obj) {return (obj === null) ? "null" : typeof (obj);}
result = variable instanceof constructor
alert(person instanceof Object); // 变量 person 是 Object 吗?alert(colors instanceof Array); // 变量 colors 是 Array 吗?alert(pattern instanceof RegExp); // 变量 pattern 是 RegExp 吗?
function Animal() {}function Bird() {}Bird.prototype = new Animal();Bird.prototype.fly = function () {//do some thingalert(‘I can fly!‘);}var pigeon = new Bird();alert(pigeon instanceof Bird); //true 毫无疑问alert(pigeon instanceof Animal); //true 由于原型链的关系alert(pigeon instanceof Object); //true
var iframe = document.createElement(‘iframe‘);document.body.appendChild(iframe);xArray = window.frames[window.frames.length-1].Array;var arr = new Array("1","2","3","4","5");alert(arr instanceof Array); // false
var iframe = document.createElement(‘iframe‘);document.body.appendChild(iframe);xArray = window.frames[window.frames.length-1].Array;var arr = new xArray("1","2","3","4","5");alert(arr instanceof Array); // falsealert(Array.isArray(arr));//true
function isArray(object) {return object!= null && typeof object == "object" && ‘splice‘ in object && ‘join‘ in object;}var liar = { splice: 1, join: 2 };alert(isArray(liar));//true,成功骗过了检测方法
var arr=[1,2,3,4];alert(Object.prototype.toString.call(arr)); //"[object Array]"
function isArray(value){return Object.prototype.toString.call(value) == "[object Array]";}
function isFunction(value){return Object.prototype.toString.call(value) == "[object Function]";}function isRegExp(value){return Object.prototype.toString.call(value) == "[object RegExp]";}
原文:http://www.cnblogs.com/star91/p/5288685.html