JavaScript 判断一个对象的数据类型。
1、isString
1 var isString1 = function (obj){ 2 return Object.prototype.toString.call(obj)==="[object String]"; 3 }; 4 5 6 var isString2 = function(obj){ 7 return (typeof obj==="string") 8 }; 9 10 11 var isString3 = function (obj) { 12 return ("" + obj) === obj; 13 };
2、isArray
1 var isArray1 = function(obj){ 2 return Object.prototype.toString.call(obj)==="[object Array]" 3 }; 4 5 var isArray2 = function(obj){ 6 return obj instanceof Array; 7 }; 8 9 var isArray3 = function(obj){ 10 return Array.isArray(obj); //需要浏览器支持 11 };
3、其他
1 var toString = Object.prototype.toString; 2 3 4 //判读一个对象是一个对象 5 _.isObject = function(obj) { 6 var type = typeof obj; 7 return type === 'function' || type === 'object' && !!obj; 8 }; 9
10 // isArguments, isFunction, isString, isNumber, isDate, isRegExp, isError. 11 _.each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp', 'Error'], function(name) { 12 _['is' + name] = function(obj) { 13 return toString.call(obj) === '[object ' + name + ']'; 14 }; 15 });