1、typeof 返回值有六种可能: “number,” “string,” “boolean,” “object,” “function,” 和 “undefined.”; typeof的运算数未定义,返回的就是 “undefined”. 运算数为数字 typeof(x) = “number” 字符串 typeof(x) = “string” 布尔值 typeof(x) = “boolean” 对象,数组和null typeof(x) = “object” 函数 typeof(x) = “function” typeof对于数组和对象返回的值都是object,那如何判断一个值是对象还是数组呢: 1.instanceof操作符 这个操作符和JavaScript中面向对象有点关系,了解这个就先得了解JavaScript中的面向对象。因为这个操作符是检测对象的原型链是否指向构造函数的prototype对象的 var arr = [1,2,3,1]; alert(arr instanceof Array); // true 2、如何判断当前值是json对象
jm.isJson = function(obj){ var isjson = typeof(obj) == "object" && Object.prototype.toString.call(obj).toLowerCase() == "[object object]" && !obj.length; return isjson; }如果传入的obj是数组的话: Object.prototype.toString.call(obj).toLowerCase() == “[object Array]”
在JavaScript里使用typeof判断数据类型,只能区分基本类型,即:number、string、undefined、boolean、object、function。 对于null、array、object来说,使用typeof都会统一返回object字符串。 要想区分对象、数组、函数、单纯使用typeof是不行的。在JS中,可以通过Object.prototype.toString方法,判断某个对象之属于哪种内置类型。 分为null、string、boolean、number、undefined、array、function、object、date、math。
**数组类型** var arr = [1,2,3]; Object.prototype.toString.call(arr); // "[object Array]"根据以上的分析,写一个函数:判断变量名arr是什么类型: 方法一:
function getArr(arr){ if(typeof (arr)=="object"){ if(Object.prototype.toString.call(arr).toLowerCase() == "[object object]" && !arr.length){ return "json" }else if(Object.prototype.toString.call(arr).toLowerCase() == "[object array]"){ return "array" } }else{ return typeof (arr) } }方法二: 此方法没有方法一判定的精确,instanceof 判断对象和数组返回的都是object;但是数组arr instanceof Array返回的是true
function getArr(arr){ if(typeof (arr)=="object"){ if(arr instanceof Array){ return "array" } }else{ return typeof (arr) } }