你但愿一个值是字符串、数字、布尔值或undefined,最佳选择是使用typeof运算符javascript
// 检测字符串 if (typeof name === "string") { antherName = name.sbustring(3); } // 检测数字 if (typeof count ==== "number") { updateCount(count); } // 检测布尔值 if (typeof found === "boolean" && found) { message("Found!"); } // 检测undefined if (typeof MyApp === "undefined") { MyApp = {}; }
typeof运算符的独特之处在于,将其用于一个未声明的变量也不会报错。未定义的变量和值为undefined的变量经过typeof都将返回""undefined"java
javascript中除了原始值以外的值都是引用。几种类置的引用类型:Object、Array、Date和Error。typeof运算符在判断这些引用类型时则显得力不从心。由于全部对象都会返回Object。typeof运算符用于null时也会返回object正则表达式
// 检测日期 if (value instanceof Date) { console.log(value.getFullYear()); } // 检测正则表达式 if (value instanceof RegExp) { if (value.test(antherValue)) { console.log("Matched"); } } // 检测Error if (value instanceof Error) { throw value; } // 检测自定义对象(惟一的方法) if (me instanceof Person) { } // 全部对象都被认为是Object的实例 if (me instanceof Object) { }
function myFunc(){} console.log(typeof myFunc === "function");
// 采用鸭式辨型的方法 function isArray(value) { return typeof value.sort === "function"; } // 优雅的解决方案 function isArray(value) { return Object.prototype.toString.call(value) === "[Object Array]"; } function isArray(value) { if (typeof Array.isArray === "function") { return Array.isArray(value); } return Object.prototype.toString.call(value) === "[Object Array]"; }
var object = { count: 0, related: null }; if ("count" in object) { } if ("related" in object) { } // IE8以及小于IE8版本中,DOM对象并不是继承自Object,所以不包含hasOwnProperty方法 // 若是对象是DOM时须要判断 if ("hasOwnProperty" in Object && Object.hasOwnProperty("related")) { }