您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

Js中如何判断变量是数组、函数或对象的代码说明

2024/3/16 4:34:29发布14次查看
数组
     ecmascript5中array.isarray是原生的判断数组的方法,ie9及以上支持。考虑到兼容性,在没有此方法的浏览器中,可以使用 object.prototype.tostring.call(obj) === '[object array]'替代。
var isarray = array.isarray || function(obj) { return object.prototype.tostring.call(obj) === '[object array]'; }
jq的确封装了一个函数jquery.inarray( value, array ) 搜索数组中指定值并返回它的索引(如果没有找到则返回-1)。
value要搜索的值。array一个数组,通过它来搜索。
function inarray1(needle,array,bool){ if(typeof needle=="string"||typeof needle=="number"){ for(var i in array){ if(needle===array[i]){ if(bool){ return i; } return true; } } return false; } }
函数
最简单且性能最好的办法就是 typeof obj == 'function'。考虑到某些版本浏览器存在的bug,最靠谱的办法是 object.prototype.tostring.call(obj) === '[object function]'。
var isfunction = function(obj) { return object.prototype.tostring.call(obj) === '[object function]'; } if(typeof /./ != 'function' && typeof int8array != 'object') { isfunction = function(obj) { return typeof obj == 'function'; } }
对象
在javascript中复杂类型是对象,函数也是对象。对上述2者使用typeof,可以分别得到'object'和'function'。另外,还要排除null值的情况,因为typeof null 得到的也是 'object'。
var isobject = function(obj) { var type = typeof obj; return type === 'function' || type === 'object' && !!obj; }
以上就是js中如何判断变量是数组、函数或对象的代码说明的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product